Example usage for javax.mail PasswordAuthentication PasswordAuthentication

List of usage examples for javax.mail PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, String password) 

Source Link

Document

Initialize a new PasswordAuthentication

Usage

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean setup() {
    try {/*from w  w w.j  a  va 2 s  .com*/
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            setAuthenticator(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(service.getEmailConfig().getUserId(),
                            service.getEmailConfig().getPassword());
                }
            });
        }

        return true;
    } catch (Exception e) {
        logger.error("Email.ERROR_0013_CONFIG_FILE_INVALID", e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /*from ww w . jav  a 2  s. c  om*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java

public void enviarEmailHtml(List<String> destinos, String msg, String titulo) {
    //       Recipient's email ID needs to be mentioned.
    String to = "";
    String rodape = "<br/><br/><br/><br/>  <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">"
            + "Esta mensagem  uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> "
            + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>"
            + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>"
            + "</div>";
    for (String d : destinos) {
        if (d.equals(destinos.get(destinos.size() - 1))) {
            to = to.concat(d);//from   w  w  w  . jav a  2s  .c  o m
        } else {
            to = to.concat(d.concat(","));
        }
    }

    // Sender's email ID needs to be mentioned
    String from = this.email;
    final String username = this.email;//change accordingly
    final String password = this.senha;//change accordingly

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", this.host);
    props.put("mail.smtp.port", "25");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject(titulo);

        // Send the actual HTML message, as big as you like
        message.setContent(msg + rodape, "text/html");

        // Send message
        Transport.send(message);

    } catch (MessagingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*w  w w.ja  va2s  .co  m*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*  ww w.  jav  a2s .  c  o  m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java

/**
 * Getting the connection to email using Mail API
 *
 * @return - Email message Store//from   w w w. j a va 2s  .co m
 * @throws ESBMailTransportIntegrationTestException - Is thrown if an error while connecting to email store
 */
private static Store getConnection() throws ESBMailTransportIntegrationTestException {
    Properties properties;
    Session session;

    properties = new Properties();
    properties.setProperty("mail.host", "imap.gmail.com");
    properties.setProperty("mail.port", "995");
    properties.setProperty("mail.transport.protocol", "imaps");

    session = Session.getInstance(properties, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(receiver + "@" + domain, String.valueOf(receiverPassword));
        }
    });
    try {
        Store store = session.getStore("imaps");
        store.connect();
        return store;
    } catch (MessagingException e) {
        log.error("Error when creating the email store ", e);
        throw new ESBMailTransportIntegrationTestException("Error when creating the email store ", e);
    }
}

From source file:Implement.DAO.CommonDAOImpl.java

@Override
public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from   ww  w.ja  v  a2 s. com*/
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(messageContent, "text/html; charset=utf-8");
    Transport.send(message);
    return true;

}

From source file:org.pentaho.platform.util.Emailer.java

public boolean setup() {
    try {/*from  w w  w.  j a v a2 s . c o  m*/
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());

        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = getEmailFromName();
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            setAuthenticator(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    String decrypted;
                    try {
                        Base64PasswordService ps = new Base64PasswordService();
                        String pass = service.getEmailConfig().getPassword();
                        if (pass.startsWith("ENC:")) {
                            decrypted = ps.decrypt(
                                    service.getEmailConfig().getPassword().substring(4, pass.length()));
                        } else {
                            decrypted = ps.decrypt(service.getEmailConfig().getPassword());
                        }
                    } catch (Exception e) {
                        decrypted = service.getEmailConfig().getPassword();
                    }
                    return new PasswordAuthentication(service.getEmailConfig().getUserId(), decrypted);
                }
            });
        }

        return true;
    } catch (Exception e) {
        logger.error("Email.ERROR_0013_CONFIG_FILE_INVALID", e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.gcrm.util.mail.MailService.java

private Session createSmtpSession(EmailSetting emailSetting) {
    final Properties props = new Properties();

    int emailProvider = emailSetting.getEmail_provider();
    String smtpUsername = null;/*w w  w . j av a 2  s . c om*/
    String smtpPassword = null;
    switch (emailProvider) {
    case EmailSetting.PROVIDER_GMAIL:
        props.setProperty("mail.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", "" + 587);
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.starttls.enable", "true");
        smtpUsername = emailSetting.getGmail_address();
        smtpPassword = emailSetting.getGmail_password();
        break;
    case EmailSetting.PROVIDER_YAHOO:
        props.setProperty("mail.host", "smtp.mail.yahoo.com");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", "" + 587);
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.starttls.enable", "true");
        smtpUsername = emailSetting.getYahoo_mail_ID();
        smtpPassword = emailSetting.getYahoo_mail_password();
        break;
    case EmailSetting.PROVIDER_OTHER:
        props.setProperty("mail.host", emailSetting.getSmtp_server());
        props.setProperty("mail.smtp.auth", String.valueOf(emailSetting.isSmtp_authentication()));
        props.setProperty("mail.smtp.port", "" + emailSetting.getSmtp_port());
        smtpUsername = emailSetting.getSmtp_username();
        smtpPassword = emailSetting.getSmtp_password();
        switch (emailSetting.getSmtp_protocol()) {
        case EmailSetting.PROTOCOL_SSL:
            props.setProperty("mail.transport.protocol", "smtps");
            break;
        case EmailSetting.PROTOCOL_TLS:
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.starttls.enable", "true");
            break;
        default:
            props.setProperty("mail.transport.protocol", "smtp");
            break;
        }
        break;
    }

    final String userName = smtpUsername;
    final String password = smtpPassword;
    return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
}

From source file:ee.cyber.licensing.service.MailService.java

public void sendExpirationNearingMail(License license) throws IOException, MessagingException {
    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");
    final String mailTo = mailServerProperties.getProperty("mailTo");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//from   w  w w  .j a  v a  2s  . c om
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "Licensing service"));
    mailMessage.setSubject("License with id " + license.getId() + " is expiring");
    mailMessage.setSentDate(new Date());
    mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    String emailBody = "This is test<br><br> Regards, <br>Licensing team";
    mailMessage.setContent(emailBody, "text/html");

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);

}