Example usage for org.apache.commons.mail Email setAuthenticator

List of usage examples for org.apache.commons.mail Email setAuthenticator

Introduction

In this page you can find the example usage for org.apache.commons.mail Email setAuthenticator.

Prototype

public void setAuthenticator(final Authenticator newAuthenticator) 

Source Link

Document

Sets the Authenticator to be used when authentication is requested from the mail server.

Usage

From source file:com.neu.controller.MessageController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");

    if (action.equalsIgnoreCase("reply")) {

        try {//from  ww  w  . j a  va2  s  .c  om

            String receiver = request.getParameter("to");
            System.out.println("Printing receiver in reply case: " + receiver);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, receiver);
            if (ub != null) {
                System.out.println("printing userEmail received from DB: " + ub.getUserEmail());

                mv.addObject("toEmail", ub.getUserEmail());
                mv.addObject("to", receiver);
            }

            mv.setViewName("reply");

        } catch (SQLException e) {
            System.out.println(e);

        }

    } else if (action.equalsIgnoreCase("sent")) {
        System.out.println("In sent case");

        try {
            String receiver = request.getParameter("to");
            String receiverEmail = request.getParameter("toEmail");

            System.out.println("printing receiver email: " + receiverEmail);

            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            UsersBean ub = run.query("select * from userstable where userName =?", user, userName);
            if (ub != null) {
                String senderEmail = ub.getUserEmail();
                System.out.println("printing senderemail: " + senderEmail);

                ResultSetHandler<MessageBean> msg = new BeanHandler<MessageBean>(MessageBean.class);
                Object[] params = new Object[4];
                params[0] = userName;
                params[1] = request.getParameter("message");
                Date d = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                String messageDate = format.format(d);
                params[2] = messageDate;
                params[3] = receiver;
                int inserts = run.update(
                        "Insert into messages (fromUser,message,messageDate,userName) values(?,?,?,?)", params);//Logic to send the email

                try {
                    Email email = new SimpleEmail();
                    email.setHostName("smtp.googlemail.com");//If a server is capable of sending email, then you don't need the authentication. In this case, an email server needs to be running on that machine. Since we are running this application on the localhost and we don't have a email server, we are simply asking gmail to relay this email.
                    email.setSmtpPort(465);
                    email.setAuthenticator(
                            new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                    email.setSSLOnConnect(true);
                    email.setFrom(senderEmail);//This email will appear in the from field of the sending email. It doesn't have to be a real email address.This could be used for phishing/spoofing!
                    email.setSubject("Thanks for Signing Up!");
                    email.setMsg("Welcome to Web tools Lab 5 Spring Application sign up email test!");
                    email.addTo(receiverEmail);//Will come from the database
                    email.send();
                } catch (Exception e) {
                    System.out.println("Email Exception" + e.getMessage());
                    e.printStackTrace();
                }
                mv.setViewName("messageSent");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());
            ex.printStackTrace();

        }

    }

    return mv;
}

From source file:com.neu.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();

    if (action.equalsIgnoreCase("login")) {
        try {/*from   ww w  . j a v a2  s  . c o  m*/
            String userName = request.getParameter("user");
            String password = request.getParameter("password");
            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[2];
            params[0] = userName;
            params[1] = password;
            UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user,
                    params);
            if (ub != null) {
                ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>(
                        MessageBean.class);
                List<MessageBean> msg = run.query("select * from messages where userName =?", messages,
                        userName);
                session.setAttribute("userName", userName);
                session.setAttribute("messageList", msg);
                mv.setViewName("userhome");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());

        }

    } else if (action.equalsIgnoreCase("logout")) {

        session.invalidate();
        mv.setViewName("index");
    } else if (action.equalsIgnoreCase("signup")) {

        System.out.println("sign up");
        //                
        //                String userName = request.getParameter("user");
        //                String password = request.getParameter("password");
        //                String emailObj = request.getParameter("emailObj");
        //                
        // System.out.println("printing details: " + userName + " " +password + " "+emailObj);
        mv.setViewName("signup");
    } else if (action.equalsIgnoreCase("signupsubmit")) {

        System.out.println("sign up submit");

        String userName = request.getParameter("user");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        System.out.println("printing details: " + userName + " " + password + " " + email);

        if (userName.equals("") || (password.equals("")) || (email.equals(""))) {
            System.out.println("empty values");
            mv.addObject("error", "true");
        }

        else {
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[3];
            params[0] = userName;
            params[1] = password;
            params[2] = email;
            QueryRunner run = new QueryRunner(ds);
            int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)",
                    params);//Logic to insert into table
            System.out.println("inserts value " + inserts);

            if (inserts > 0) {
                mv.addObject("success", "true");
                Email emailObj = new SimpleEmail();
                emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj.
                emailObj.setSmtpPort(465);
                emailObj.setAuthenticator(
                        new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                emailObj.setSSLOnConnect(true);
                emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing!
                emailObj.setSubject("TestMail");
                emailObj.setMsg("This is spring MVC Contact Application sending you the email");
                emailObj.addTo(email);//Will come from the sign up details
                emailObj.send();
            }

        }

        mv.setViewName("signup");
    }

    return mv;
}

From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java

public void sendNotificationSMS(String send_sms_to_provider, String send_sms_to, String from, String username,
        String password, String hostname, String portno, boolean setSSLOnConnectFlag, String subject,
        String message) {// w w  w  .  jav  a  2s . c  o m
    try {
        send_sms_to_provider = settings.getString(TO_SMS_PROVIDER_PROPERTY);
        send_sms_to = settings.getString(TO_SMS_PROPERTY);

        Email smsObject = new SimpleEmail();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String dateStr = dateFormat.format(cal.getTime());
        smsObject.setHostName(hostname);
        smsObject.setSmtpPort(Integer.parseInt(portno));
        smsObject.setAuthenticator(new DefaultAuthenticator(username, password));
        smsObject.setSSL(true);
        smsObject.setFrom(from);
        smsObject.setSubject("");
        smsObject.setMsg("Sonar analysis completed successfully at " + dateStr + " . Please visit "
                + settings.getString("sonar.host.url") + " for more details!");
        //multiple SMS recipients.
        String[] addrs = StringUtils.split(to_email, "\t\r\n;, ");
        for (String addr : addrs) {
            smsObject.addTo(send_sms_to);
        }
        smsObject.send();
    } catch (EmailException e) {
        throw new SonarException("Unable to send sms", e);
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }
}

From source file:io.mapzone.controller.email.EmailService.java

public void send(Email email) throws EmailException {
    String env = System.getProperty("io.mapzone.controller.SMTP");
    if (env == null) {
        throw new IllegalStateException(
                "Environment variable missing: io.mapzone.controller.SMTPP. Format: <host>|<login>|<passwd>|<from>");
    }//from   w w w  .ja  v a 2s.c o m
    String[] parts = StringUtils.split(env, "|");
    if (parts.length < 3 || parts.length > 4) {
        throw new IllegalStateException(
                "Environment variable wrong: io.mapzone.controller.SMTP. Format: <host>|<login>|<passwd>|<from> : "
                        + env);
    }

    email.setDebug(true);
    email.setHostName(parts[0]);
    //email.setSmtpPort( 465 );
    //email.setSSLOnConnect( true );
    email.setAuthenticator(new DefaultAuthenticator(parts[1], parts[2]));
    if (email.getFromAddress() == null && parts.length == 4) {
        email.setFrom(parts[3]);
    }
    if (email.getSubject() == null) {
        throw new EmailException("Missing subject.");
    }
    email.send();
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

/**
 * Send the actual email.//w  w w.  java 2  s  .c om
 * 
 * @param oid
 * @param from
 * @param recipient
 * @param subject
 * @param body
 * @return
 */
public boolean email(String oid, String from, String recipient, String subject, String body) {
    try {
        Email email = new SimpleEmail();
        log.debug("Email host: " + host);
        log.debug("Email port: " + port);
        log.debug("Email username: " + username);
        log.debug("Email from: " + from);
        log.debug("Email to: " + recipient);
        log.debug("Email Subject is: " + subject);
        log.debug("Email Body is: " + body);
        email.setHostName(host);
        email.setSmtpPort(Integer.parseInt(port));
        email.setAuthenticator(new DefaultAuthenticator(username, password));
        // the method setSSL is deprecated on the newer versions of commons
        // email...
        email.setSSL("true".equalsIgnoreCase(ssl));
        email.setTLS("true".equalsIgnoreCase(tls));
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(body);
        if (recipient.indexOf(",") >= 0) {
            String[] recs = recipient.split(",");
            for (String rec : recs) {
                email.addTo(rec);
            }
        } else {
            email.addTo(recipient);
        }
        email.send();
    } catch (Exception ex) {
        log.debug("Error sending notification mail for oid:" + oid, ex);
        return false;
    }
    return true;
}

From source file:com.doculibre.constellio.wicket.panels.admin.indexing.AdminIndexingPanel.java

private void sendEmail(String hostName, int smtpPort, DefaultAuthenticator authenticator, String sender,
        String subject, String message, String receiver) throws EmailException {
    Email email = new SimpleEmail();
    email.setHostName(hostName);// w ww .j a v  a  2 s .co  m
    email.setSmtpPort(smtpPort);
    email.setAuthenticator(authenticator);
    email.setFrom(sender);
    email.setSubject(subject);
    email.setMsg(message);
    email.addTo(receiver);
    email.send();
}

From source file:com.patrolpro.beans.SignupClientBean.java

public String sendEmail() {
    try {// w  w  w.ja v  a2s  . com
        boolean isValid = validateInformation();

        if (isValid) {
            StringBuilder emailMessage = new StringBuilder();
            emailMessage.append("Contact Name: " + this.contactName + "\r\n");
            emailMessage.append("Contact Email: " + this.contactEmail + "\r\n");
            emailMessage.append("Contact Phone: " + this.contactPhone + "\r\n");
            emailMessage.append("Company Name: " + this.companyName + "\r\n");
            emailMessage.append(message);

            Email htmlEmail = new SimpleEmail();
            if (message == null || message.length() == 0) {
                message = "No message was provided by the user.";
            }
            htmlEmail.setFrom("signup@patrolpro.com");
            htmlEmail.setSubject("Trial Account Email!");
            htmlEmail.addTo("rharris@ainteractivesolution.com");
            htmlEmail.addTo("ijuneau@ainteractivesolution.com");
            htmlEmail.addCc("jc@champ.net");
            //htmlEmail.setHtmlMsg(emailMessage.toString());
            htmlEmail.setMsg(emailMessage.toString());
            //htmlEmail.setTextMsg(emailMessage.toString());

            htmlEmail.setDebug(true);
            htmlEmail.setAuthenticator(new MailAuthenticator("schedfox", "Sch3dF0x4m3"));
            htmlEmail.setHostName("mail2.champ.net");
            htmlEmail.setSmtpPort(587);
            htmlEmail.send();
            return "sentEmail";
        }
    } catch (Exception exe) {

    }
    return "invalid";
}

From source file:JavaMail.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//  ww w  . j  a v  a 2s  .co  m
        String from = jTextField1.getText();
        String to = jTextField2.getText();
        String subject = jTextField3.getText();
        String content = jTextArea1.getText();
        Email email = new SimpleEmail();
        String provi = prov.getSelectedItem().toString();
        if (provi.equals("Gmail")) {
            email.setHostName("smtp.gmail.com");
            email.setSmtpPort(465);
            serverlink = "smtp.gmail.com";
            serverport = 465;
        }
        if (provi.equals("Outlook")) {
            email.setHostName("smtp-mail.outlook.com");
            serverlink = "smtp-mail.outlook.com";
            email.setSmtpPort(25);
            serverport = 25;
        }
        if (provi.equals("Yahoo")) {
            email.setHostName("smtp.mail.yahoo.com");
            serverlink = "smtp.mail.yahoo.com";
            email.setSmtpPort(465);
            serverport = 465;
        }
        System.out.println("Initializing email sending sequence");
        System.out.println("Connecting to " + serverlink + " at port " + serverport);
        JPanel panel = new JPanel();
        JLabel label = new JLabel(
                "Enter the password of your email ID to connect with your Email provider." + "\n");
        JPasswordField pass = new JPasswordField(10);
        panel.add(label);
        panel.add(pass);
        String[] options = new String[] { "OK", "Cancel" };
        int option = JOptionPane.showOptionDialog(null, panel, "Enter Email ID Password", JOptionPane.NO_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
        if (option == 0) // pressing OK button
        {
            char[] password = pass.getPassword();
            emailpass = new String(password);
        }
        email.setAuthenticator(new DefaultAuthenticator(from, emailpass));
        email.setSSLOnConnect(true);
        if (email.isSSLOnConnect() == true) {
            System.out.println("This server requires SSL/TLS authentication.");
        }
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(content);
        email.addTo(to);
        email.send();
        JOptionPane.showMessageDialog(null, "Message sent successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.aurel.track.util.emailHandling.MailSender.java

private Email setAuthMode(Email email) {
    Integer smtpAuthMode = new Integer(-1);
    try {/* w w  w . j  av a 2s  .  co m*/
        smtpAuthMode = Integer.valueOf(smtpMailSettings.getAuthMode());
    } catch (Exception e) {
    }

    switch (smtpAuthMode) {
    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_TO_INCOMING_MAIL_SERVER_BEFORE_SENDING: {
        IncomingMailSettings incomingMailSettings = smtpMailSettings.getIncomingMailSettings();
        String mailReceivingServerName = null;
        String mailReceivingUser = null;
        String mailReceivingPassword = null;
        if (incomingMailSettings != null) {
            mailReceivingServerName = incomingMailSettings.getServerName();
            mailReceivingUser = incomingMailSettings.getUser();
            mailReceivingPassword = incomingMailSettings.getPassword();
        }
        boolean newPopBeforeSmtp = true; // TODO We should check in our POP3 session first
        email.setPopBeforeSmtp(newPopBeforeSmtp, mailReceivingServerName, mailReceivingUser,
                mailReceivingPassword);
        break;
    }

    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_USING_SMTP_SETTINGS: {
        LOGGER.debug("Connect to SMTP server using SMTP user/password ...");
        if (smtpMailSettings.getUser() == null || "".equals(smtpMailSettings.getUser().trim())) {
            LOGGER.warn("No SMTP user found by 'Connect using SMTP settings'");
        }
        email.setAuthenticator(
                new DefaultAuthenticator(smtpMailSettings.getUser(), smtpMailSettings.getPassword()));
        break;
    }

    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_WITH_SAME_SETTINGS_AS_INCOMING_MAIL_SERVER: {
        IncomingMailSettings incomingMailSettings = smtpMailSettings.getIncomingMailSettings();
        String mailReceivingUser = null;
        String mailReceivingPassword = null;
        if (incomingMailSettings != null) {
            mailReceivingUser = incomingMailSettings.getUser();
            mailReceivingPassword = incomingMailSettings.getPassword();
        }
        LOGGER.debug("Connect to SMTP server using incoming mail (POP3 or IMAP) user " + mailReceivingUser
                + " passord specified "
                + new Boolean(mailReceivingPassword != null && mailReceivingPassword.length() > 0).toString());
        if (mailReceivingUser == null || "".equals(mailReceivingUser.trim())) {
            LOGGER.warn(
                    "No incoming mail user (POP3 or IMAP) found by 'Connect with same settings as incoming mail server'");
        }
        email.setAuthenticator(new DefaultAuthenticator(mailReceivingUser, mailReceivingPassword));
        break;
    }
    }
    return email;
}

From source file:easycar.controller.BookingListController.java

public void emailRemind() {
    Email email = new SimpleEmail();
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);//www  .  j a va2  s  .c om
    email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
    email.setSSLOnConnect(true);
    try {
        email.setFrom("easycarremind@gmail.com");
        email.setSubject("Reminder to return car");
        email.setMsg("Dear " + selectedBooking.getCustomerName()
                + ",\n\nPlease note that you are supposed to return the car with id "
                + selectedBooking.getCarId() + " to us on " + selectedBooking.getEndDateToDisplay()
                + "\n\nBest regards,\nEasy Car Team.");
        email.addTo(selectedBooking.getCustomerEmail());
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }

    selectedBooking.setLastEmailRemindDate(getZeroTimeDate(new Date()));
    try {
        bookingService.editBooking(selectedBooking);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FacesContext.getCurrentInstance().addMessage("messageDetailDialog", new FacesMessage(
            FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
}