Example usage for javax.mail Authenticator Authenticator

List of usage examples for javax.mail Authenticator Authenticator

Introduction

In this page you can find the example usage for javax.mail Authenticator Authenticator.

Prototype

Authenticator

Source Link

Usage

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param config//from  www.  j a v a 2s  .  co  m
 * @throws Exception
 */
public MailSender(final MailConfiguration config) throws Exception {

    this.config = config;

    Properties prop = new Properties();

    if (config.isSsl()) {
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", String.valueOf(config.getPort()));
    }

    prop.setProperty("mail.transport.protocol", config.getProtocol());
    prop.setProperty("mail.smtp.host", config.getHost());
    prop.setProperty("mail.smtp.port", String.valueOf(config.getPort()));
    log.info("smtp host:" + config.getHost() + " port:" + config.getPort());
    prop.setProperty("mail.smtp.connectiontimeout", String.valueOf(config.getConnectionTimeout()));
    prop.setProperty("mail.smtp.timeout", String.valueOf(config.getReadTimeout()));

    prop.setProperty("mail.debug", String.valueOf(config.isDebug()));

    if (config.getUsername() != null && config.getUsername().length() != 0) {
        prop.setProperty("mail.smtp.auth", "true");

        session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        });
    } else {
        session = Session.getInstance(prop);
    }
    log.info("smtp host:" + config.getHost());
}

From source file:io.kodokojo.service.SmtpEmailSender.java

@Override
public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content,
        boolean htmlContent) {
    if (CollectionUtils.isEmpty(to)) {
        throw new IllegalArgumentException("to must be defined.");
    }/*from   w w  w . j  a  v  a 2 s  .  co  m*/
    if (isBlank(content)) {
        throw new IllegalArgumentException("content must be defined.");
    }
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    try {
        message.setFrom(from);
        message.setSubject(subject);
        InternetAddress[] toInternetAddress = convertToInternetAddress(to);
        message.setRecipients(Message.RecipientType.TO, toInternetAddress);
        if (CollectionUtils.isNotEmpty(cc)) {
            InternetAddress[] ccInternetAddress = convertToInternetAddress(cc);
            message.setRecipients(Message.RecipientType.CC, ccInternetAddress);
        }
        if (CollectionUtils.isNotEmpty(ci)) {
            InternetAddress[] ciInternetAddress = convertToInternetAddress(ci);
            message.setRecipients(Message.RecipientType.BCC, ciInternetAddress);
        }
        if (htmlContent) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        message.setHeader("X-Mailer", "Kodo Kojo mailer");
        message.setSentDate(new Date());
        Transport.send(message);

    } catch (MessagingException e) {
        LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e);
    }
}

From source file:eagle.common.email.EagleMailClient.java

public EagleMailClient(AbstractConfiguration configuration) {
    try {/*  ww  w  .  j a  va 2s . c o m*/
        ConcurrentMapConfiguration con = (ConcurrentMapConfiguration) configuration;
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();

        con.setProperty("mail.transport.protocol", "smtp");
        final Properties config = con.getProperties();
        if (Boolean.parseBoolean(config.getProperty(AUTH_CONFIG))) {
            session = Session.getDefaultInstance(config, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(config.getProperty(USER_CONFIG),
                            config.getProperty(PWD_CONFIG));
                }
            });
        } else
            session = Session.getDefaultInstance(config, new Authenticator() {
            });
        final String debugMode = config.getProperty(DEBUG_CONFIG, "false");
        final boolean debug = Boolean.parseBoolean(debugMode);
        session.setDebug(debug);
    } catch (Exception e) {
        LOG.error("Failed connect to smtp server", e);
    }
}

From source file:net.ymate.module.mailsender.MailSendServerCfgMeta.java

public Session createIfNeed() {
    if (__mailSession == null) {
        synchronized (this) {
            if (__mailSession == null) {
                Properties _props = new Properties();
                _props.put("mail.smtp.host", smtpHost);
                _props.put("mail.smtp.auth", needAuth);
                _props.put("mail.transport.protocol", "smtp");
                if (tlsEnabled) {
                    _props.put("mail.smtp.starttls.enable", true);
                    _props.put("mail.smtp.socketFactory.port", smtpPort);
                    _props.put("mail.smtp.socketFactory.class", StringUtils
                            .defaultIfBlank(socketFactoryClassName, "javax.net.ssl.SSLSocketFactory"));
                    _props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
                } else {
                    _props.put("mail.smtp.port", smtpPort);
                }/*  w w w  . ja  v  a 2 s  .  c om*/
                //
                __mailSession = Session.getInstance(_props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(smtpUsername, smtpPassword);
                    }
                });
                __mailSession.setDebug(debugEnabled);
            }
        }
    }
    return __mailSession;
}

From source file:org.openmrs.module.sync.SyncMailUtil.java

public static Session createSession(Map<String, String> settings) {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", settings.get(MAIL_TRANSPORT_PROTOCOL));
    props.setProperty("mail.smtp.host", settings.get(MAIL_SMTP_HOST));
    props.setProperty("mail.smtp.port", settings.get(MAIL_SMTP_PORT));
    props.setProperty("mail.smtp.auth", settings.get(MAIL_SMTP_AUTH));
    props.setProperty("mail.smtp.starttls.enable", settings.get(MAIL_SMTP_STARTTLS_ENABLE));
    props.setProperty("mail.from", settings.get(MAIL_FROM));
    props.setProperty("mail.debug", settings.get(MAIL_DEBUG));

    final String mailUser = settings.get(MAIL_USER);
    final String mailPw = settings.get(MAIL_PASSWORD);

    Authenticator auth = new Authenticator() {
        @Override//from   w  w w  .  ja va2  s. c o m
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUser, mailPw);
        }
    };
    return Session.getInstance(props, auth);
}

From source file:com.szmslab.quickjavamail.utils.MailProperties.java

/**
 * ????//from w  ww.j a va 2s . co  m
 *
 * @param userName
 *            ??
 * @param password
 *            
 * @return ?
 */
public MailProperties authenticate(final String userName, final String password) {
    if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
        if (protocol.startsWith("smtp")) {
            setString(String.format("mail.%s.auth", protocol), Boolean.TRUE.toString());
        }
    }
    return this;
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

public void send() throws AxisFault {

    try {/*from   w  w  w.ja v a 2 s.  co m*/

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.apache.axis2.transport.mail.server.SMTPWorker.java

private String processInput(String input) {
    if (input == null) {
        return Constants.COMMAND_UNKNOWN;
    }/* www .j ava 2s  . c  o m*/

    if ((mail != null) && transmitionEnd) {
        return Constants.COMMAND_TRANSMISSION_END;
    }

    if (input.startsWith("MAIL")) {
        mail = new MimeMessage(Session.getInstance(new Properties(), new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return null;
            }
        }));

        int start = input.indexOf("<") + 1;
        int end;

        if (start <= 0) {
            start = input.indexOf("FROM:") + 5;
            end = input.length();
        } else {
            end = input.indexOf(">");
        }

        String from = input.substring(start, end);

        if ((from != null) && from.trim().length() != 0) {

            // TODO this is an ugly hack to get the from address in. There
            // should be a better way to do this.
            MailAddress mailFrom[] = new MailAddress[1];

            mailFrom[0] = new MailAddress(from);

            try {
                mail.addFrom(mailFrom);
            } catch (MessagingException e) {
                log.info(e.getMessage());
            }
        }

        return Constants.MAIL_OK;
    }

    if (input.startsWith("HELO")) {
        return Constants.HELO_REPLY;
    } else if (input.startsWith("RCPT")) {

        int start = input.indexOf("<") + 1;
        int end;

        if (start <= 0) {
            start = input.indexOf("TO:") + 3;
            /*
             * if(!input.endsWith(domain)){ System.out.println("ERROR: wrong
             * donmain name"); return Constants.RCPT_ERROR; }
             */
        } else {

            /*
             * if(!input.endsWith(domain + ">")){ System.out.println("ERROR:
             * wrong donmain name"); return Constants.RCPT_ERROR; }
             */
        }

        end = input.indexOf(">");

        String toStr = input.substring(start, end);

        try {
            mail.addRecipient(Message.RecipientType.TO, new MailAddress(toStr));
            receivers.add(toStr);
        } catch (MessagingException e) {
            log.info(e.getMessage());
        }

        return Constants.RCPT_OK;
    } else if (input.equalsIgnoreCase("DATA")) {
        dataWriting = true;

        return Constants.DATA_START_SUCCESS;
    } else if (input.equalsIgnoreCase("QUIT")) {
        dataWriting = true;
        transmitionEnd = true;

        return Constants.COMMAND_TRANSMISSION_END;
    } else if (input.equals(".")) {
        dataWriting = false;

        return Constants.DATA_END_SUCCESS;
    } else if (input.length() == 0 && !bodyData) {
        bodyData = true;

        return null;
    } else if ((mail != null) && dataWriting) {
        try {
            if (bodyData) {
                temp += input;
                mail.setContent(temp, "text/xml"); //Since this is for axis2 :-)
            } else {
                mail.addHeaderLine(input);
            }
        } catch (MessagingException e) {
            log.info(e.getMessage());
        }

        return null;
    } else {
        return Constants.COMMAND_UNKNOWN;
    }
}

From source file:org.wso2.carbon.registry.eventing.MimeEmailMessageHandler.java

/**
 *
 * @param configContext ConfigurationContext
 * @param message Mail body//from  ww w  .ja v a2 s  .  c  o  m
 * @param subject Mail Subject
 * @param toAddress email to address
 * @throws RegistryException Registry exception
 */
public void sendMimeMessage(ConfigurationContext configContext, String message, String subject,
        String toAddress) throws RegistryException {
    Properties props = new Properties();
    if (configContext != null && configContext.getAxisConfiguration().getTransportOut("mailto") != null) {
        List<Parameter> params = configContext.getAxisConfiguration().getTransportOut("mailto").getParameters();
        for (Parameter parm : params) {
            props.put(parm.getName(), parm.getValue());
        }
    }
    if (threadPoolExecutor == null) {
        threadPoolExecutor = new ThreadPoolExecutor(MIN_THREAD, MAX_THREAD, DEFAULT_KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000));
    }
    String smtpFrom = props.getProperty(MailConstants.MAIL_SMTP_FROM);

    try {
        smtpFromAddress = new InternetAddress(smtpFrom);
    } catch (AddressException e) {
        log.error("Error in retrieving smtp address");
        throw new RegistryException("Error in transforming smtp address");
    }
    final String smtpUsername = props.getProperty(MailConstants.MAIL_SMTP_USERNAME);
    final String smtpPassword = props.getProperty(MailConstants.MAIL_SMTP_PASSWORD);
    if (smtpUsername != null && smtpPassword != null) {
        MimeEmailMessageHandler.session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        MimeEmailMessageHandler.session = Session.getInstance(props);
    }
    threadPoolExecutor.submit(new EmailSender(toAddress, subject, message.toString(), "text/html"));
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

/**
 * Set SMTP credential//  w ww  .j  a v a 2 s.  c  om
 *
 * @param user
 * @param pass
 */
public void setCredentials(final String user, final String pass) {
    config.setProperty("mail.smtp.auth", "true");
    this.auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pass);
        }
    };
    session = null;
}