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:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }//from  w w  w. java  2  s. c o  m

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/*from   w ww .  ja  v a  2  s.  c o m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Open mail session with the SMTP server using the given credentials. Will
 * use no authentication if strUsername is null or blank.
 *
 * @param strHost The SMTP name or IP address.
 * @param nPort The port to use/*  ww w  . j av  a  2  s .  com*/
 * @param strUsername the username
 * @param strPassword the password
 * @return the mails session object
 */
protected static Session getMailSession(String strHost, int nPort, final String strUsername,
        final String strPassword) {
    String strDebug = AppPropertiesService.getProperty(PROPERTY_MAIL_SESSION_DEBUG, Boolean.FALSE.toString());
    boolean bSessionDebug = Boolean.parseBoolean(strDebug);

    // Initializes a mail session with the SMTP server
    Properties props = System.getProperties();
    props.put(MAIL_HOST, strHost);
    props.put(MAIL_TRANSPORT_PROTOCOL, SMTP);
    props.put(MAIL_PROPTOCOL_HOST, strHost);
    props.put(MAIL_PROPTOCOL_PORT, nPort);

    Authenticator auth;

    if (StringUtils.isNotBlank(strUsername)) {
        props.put(MAIL_SMTP_AUTH, TRUE);
        // using authenticator class that return a PasswordAuthentication
        auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(strUsername, strPassword);
            }
        };
    } else {
        // no authentication data provided, no authenticator
        auth = null;
    }

    Session mailSession = Session.getDefaultInstance(props, auth);
    // Activate debugging
    mailSession.setDebug(bSessionDebug);

    return mailSession;
}

From source file:com.sonicle.webtop.core.app.WebTopSession.java

public javax.mail.Session getMailSession() {
    synchronized (lock1) {
        UserProfileId pid = getProfileId();
        if (pid != null && mailSession == null) {
            CoreServiceSettings css = new CoreServiceSettings(CoreManifest.ID, pid.getDomainId());
            String smtphost = css.getSMTPHost();
            int smtpport = css.getSMTPPort();
            boolean starttls = css.isSMTPStartTLS();
            boolean auth = css.isSMTPAuthentication();
            Properties props = new Properties(System.getProperties());
            //props.setProperty("mail.socket.debug", "true");
            //props.setProperty("mail.imap.parse.debug", "true");
            props.setProperty("mail.smtp.host", smtphost);
            props.setProperty("mail.smtp.port", "" + smtpport);
            if (starttls) {
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.ssl.trust", "*");
                props.put("mail.smtp.ssl.checkserveridentity", "false");
            }/*w  w  w  .  jav a  2s  . c  o m*/
            props.setProperty("mail.imaps.ssl.trust", "*");
            props.setProperty("mail.imap.folder.class", "com.sonicle.mail.imap.SonicleIMAPFolder");
            props.setProperty("mail.imaps.folder.class", "com.sonicle.mail.imap.SonicleIMAPFolder");
            props.setProperty("mail.imap.enableimapevents", "true"); // Support idle events
            Authenticator authenticator = null;
            if (auth) {
                props.setProperty("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
                        String login = principal.getFullInternetName();
                        String password = new String(principal.getPassword());
                        //logger.info("getPasswordAuthentication: "+login+" / *****");
                        return new PasswordAuthentication(login, password);
                    }

                };
            }
            mailSession = javax.mail.Session.getInstance(props, authenticator);
        }
    }
    return mailSession;
}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();

    props.setProperty("mail.smtp.host", this.reset.getSmtpServer());
    props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort()));
    props.setProperty("mail.smtp.user", reset.getSmtpUser());
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS()));
    //props.setProperty("mail.debug", "true");
    //props.setProperty("mail.socket.debug", "true");

    if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost());
    }/*from   www. j  a  va 2 s  . c om*/

    if (reset.isUseSocks()) {

        props.setProperty("mail.smtp.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort()));
        props.setProperty("mail.smtps.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword());
        }
    });
    //Session session = Session.getInstance(props, null);
    session.setDebugOut(System.out);
    //session.setDebug(true);
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);
    msgToSend.setText(msg.msg);

    msgToSend.saveChanges();
    Transport.send(msgToSend);
    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:org.liveSense.service.email.EmailSendJobEventHandler.java

private javax.mail.Session getMailSession() {

    java.util.Properties properties = new java.util.Properties();
    Authenticator authenticator = null;
    if (StringUtils.isNotEmpty(smtpUserName)) {
        authenticator = new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUserName, smtpPassword);
            }//ww  w  . j a  v  a2 s .  c  o  m
        };
        properties.setProperty("mail.smtp.auth", "true");
    }

    properties.setProperty("mail.smtp.host", smtpHost);
    properties.setProperty("mail.smtp.port", Long.toString(smtpPort));
    properties.setProperty("mail.smtp.connectiontimeout", Long.toString(smtpConnectionTimeout));
    properties.setProperty("mail.smtp.timeout", Long.toString(smtpConnectionTimeout));
    properties.setProperty("mail.smtp.ssl.enable", Boolean.toString(smtpSslEnable));
    properties.setProperty("mail.smtp.startls.enable", Boolean.toString(smtpStartTlsEnable));
    if (smtpSslEnable) {
        properties.setProperty("mail.smtp.socketFactory.port", Long.toString(smtpPort));
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }
    if (smtpDebug) {
        properties.setProperty("mail.debug", "true");
        StringWriter writer = new StringWriter();
        try {
            properties.store(writer, "");
        } catch (IOException e) {
        }
        log.info(writer.toString());
    }

    return javax.mail.Session.getInstance(properties, authenticator);
}

From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java

private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed
    // TODO add your handling code here:

    int selectedRow = productTable.getSelectedRow();
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select a Product from the Table");
        return;//w w  w.  j av  a  2 s .  c o m
    }

    Product product = (Product) productTable.getValueAt(selectedRow, 0);
    int quantity = (Integer) quantitySpinner.getValue();
    if (quantity == 0) {
        JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!");
        return;
    }

    if (product != null) {
        updateQuantity(product, quantity, SUBTRACT);
    }
    String medName = product.getProdName();

    Employee patient = (Employee) patientCombo1.getSelectedItem();
    patient.getMedicalRecord().setMedicinePrescribed(medName);
    String email = patient.getEmail();

    if (email.trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!");
        return;
    }

    if (isValidEmailAddress(email)) {
        String uuid = UUID.randomUUID().toString();
        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");

        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");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
            }

        }

        );
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Prescribed Medicines");
            message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:"
                    + quantity + '\n' + "The unique barcode is:" + uuid);
            Transport.send(message);
            populateTable();
            JOptionPane.showMessageDialog(null, "message sent");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "message failed");
        }

    } else {
        JOptionPane.showMessageDialog(null, "Invalid Email Id");
        return;
    }

    //        String uuid = UUID.randomUUID().toString();
    //        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");
    //        
    //        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");
    //
    //            Session  session = Session.getDefaultInstance(props,
    //                    new javax.mail.Authenticator(){
    //                        protected PasswordAuthentication getPasswordAuthentication(){
    //      return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
    //                    }
    //   
    //            }
    //
    //   );
    //        try{
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
    //            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
    //            message.setSubject("Prescribed Medicines");
    //            message.setText("The medicine Prescribed is :" +medName + '\n'+
    //                            "The Quantity authorized is:"+quantity + '\n'+
    //                            "The unique barcode is:"+uuid);
    //                Transport.send(message);
    //                    populateTable();
    //                    JOptionPane.showMessageDialog(null,"message sent");
    //            }catch(Exception e){
    //                JOptionPane.showMessageDialog(null,"message failed");
    //            }

}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    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");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//from  ww w  .j  a  va2s  .c  o  m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * @see javax.mail.Authenticator#getPasswordAuthentication()
 *//*from  ww w . j  a va2  s .com*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(this.user, this.password);
}

From source file:GUI.DashbordAdminFrame.java

private void btnEnvMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvMailActionPerformed
    // TODO add your handling code here:
    String to = null;// ww w.ja  va 2s . c o  m
    UserDao u = new UserDao();
    List listeTo = new ArrayList();
    listeTo = u.findAllEmail();

    String from = "allfordealpi@gmail.com";
    final String username = "allfordealpi@gmail.com";
    final String password = "pidev2016";

    String host = "smtp.gmail.com";

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

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

    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        for (Object o : listeTo) {

            to = (String) o;
            System.out.println(to);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            message.setSubject(tfObjet.getText());

            message.setText(taContenu.getText());

            // Send message
            Transport.send(message);
        }
        System.out.println("Sent message successfully....");

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

}