Example usage for org.apache.commons.mail HtmlEmail setSslSmtpPort

List of usage examples for org.apache.commons.mail HtmlEmail setSslSmtpPort

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail setSslSmtpPort.

Prototype

public void setSslSmtpPort(final String sslSmtpPort) 

Source Link

Document

Sets the SSL port to use for the SMTP transport.

Usage

From source file:com.jredrain.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(0);//from   www  .  ja  v a2  s . co m
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;
    try {
        log.setType(RedRain.MsgType.EMAIL.getValue());
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("redrain");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {

        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));

            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);
            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(RedRain.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    }

}

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

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {/*  w  ww  . j  a  v a 2  s. c  o  m*/

        // Create the email message
        //MultiPartEmail email = new MultiPartEmail();   
        StringBuilder strHtmlContentSummary = new StringBuilder();
        System.out.println("Analysis -  Sonar Email Notification");
        from = settings.getString("sonar.jd.smptp.username");
        System.out.println("from=>" + from);
        to_email = settings.getString("sonar.jd.smptp.to");
        System.out.println("to_email=>" + to_email);

        to_email_name = settings.getString("sonar.jd.smptp.to_name");
        System.out.println("to_email_name=>" + to_email_name);

        username = settings.getString("sonar.jd.smptp.username");
        System.out.println("username=>" + username);
        password = settings.getString("sonar.jd.smptp.password");
        System.out.println("password=>" + password);
        hostname = settings.getString("sonar.jd.smptp.host");
        System.out.println("hostname=>" + hostname);
        portno = settings.getString("sonar.jd.smptp.sslport");
        System.out.println("portno=>" + portno);
        setSSLOnConnectFlag = settings.getBoolean("sonar.jd.smptp.set_ssl_on_connect");
        System.out.println("setSSLOnConnectFlag=>" + String.valueOf(setSSLOnConnectFlag));
        subject = settings.getString("sonar.jd.smptp.subject");
        System.out.println("subject=>" + subject);
        message = settings.getString("sonar.jd.smptp.message");
        System.out.println("message=>" + message);

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostname);
        email.setSslSmtpPort(portno);
        if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) {
            email.setAuthentication(username, password);
        }
        //email.setSSLOnConnect(setSSLOnConnectFlag);
        email.setSSL(setSSLOnConnectFlag);
        String[] addrs = StringUtils.split(to_email, "\t\r\n;, ");
        for (String addr : addrs) {
            email.addTo(addr);
        }
        //email.addTo(to_email,to_email_name);
        email.setFrom(from);
        email.setSubject(subject);
        //email.setMsg(message);

        // embed the image and get the content id   
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo - 1");

        System.out.println("Print Entries from Analysis Data Map.");
        int i = 1;
        strHtmlContentSummary.append("<html><body>The apache logo - <img src=\"cid:" + cid
                + "\"><br><br><br><b><center>Metric Information:-</center></b><br><table border='2'>");
        for (Map.Entry<String, String> entry : reportDataMap.entrySet()) {
            strHtmlContentSummary
                    .append("<tr><td>" + entry.getKey() + ":</td><td>" + entry.getValue() + "</td></tr>");
            i++;
        }
        strHtmlContentSummary.append("</table></body></html>");
        System.out.println(strHtmlContentSummary.toString());
        // set the html message
        email.setHtmlMsg(strHtmlContentSummary.toString());
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(reportname);

        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sonar Analysis Report" + reportname);
        attachment.setName(reportname);
        email.attach(attachment);
        // send the email
        System.out.println("Sending the Email");
        email.send();
    } catch (EmailException e) {
        throw new SonarException("Unable to send email", e);
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

}

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;/*w  w  w  . java 2 s.  co  m*/
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

From source file:org.gravidence.gravifon.email.ApacheCommonsEmailSender.java

@Override
public boolean send(String toAddress, String toName, String subject, String htmlMessage, String textMessage) {
    HtmlEmail email = new HtmlEmail();

    email.setHostName(host);//from   w  w  w  .ja va  2 s .c o  m
    email.setSslSmtpPort(port);
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    email.setSSLOnConnect(true);

    try {
        if (StringUtils.isBlank(toName)) {
            email.addTo(toAddress);
        } else {
            email.addTo(toAddress, toName);
        }
        email.setFrom(fromAddress, fromName);

        email.setSubject(subject);

        if (htmlMessage != null) {
            email.setHtmlMsg(htmlMessage);
        }
        if (textMessage != null) {
            email.setTextMsg(textMessage);
        }

        email.send();
    } catch (EmailException ex) {
        // TODO think about throwing GravifonException
        LOGGER.warn(String.format("Failed to send an email to %s", toAddress), ex);

        return false;
    }

    return true;
}

From source file:org.jcronjob.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    try {// ww  w.  j  a v  a  2  s  .  c  o m
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("cronjob");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();

        Log log = new Log();
        log.setType(0);
        log.setWorkerId(workId);
        log.setMessage(content);
        for (String receiver : emailAddress.split(",")) {
            log.setReceiver(receiver);
            log.setSendTime(new Date());
            homeService.saveLog(log);
        }
        log.setType(1);
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));

            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);

            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setReceiver(mobile);
            log.setResult(message);
            log.setSendTime(new Date());
            homeService.saveLog(log);
            logger.info(message);

        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

}

From source file:org.meerkat.network.MailManager.java

/**
 * sendEmail//from  w w w. ja va2s . co  m
 * @param subject
 * @param message
 */
public final void sendEmail(String subject, String message) {
    this.refreshSettings();

    HtmlEmail email = new HtmlEmail();
    email.setHostName(getSMTPServer());
    email.setSmtpPort(Integer.valueOf(getSMTPPort()));
    email.setSubject(subject);
    try {
        email.setHtmlMsg(message);
    } catch (EmailException e2) {
        log.error("Error in mail message. ", e2);
    }

    // SMTP security
    String security = getSMTPSecurity();
    if (security.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (security.equalsIgnoreCase("SSL/TLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(getSMTPPort()));
    }
    email.setAuthentication(getSMTPUser(), getSMTPPassword());

    try {
        String[] toList = getTO().split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        log.error("EmailException: addTo(" + getTO() + "). " + e1.getMessage());
    }

    try {
        email.setFrom(getFROM());
    } catch (EmailException e1) {
        log.error("EmailException: setFrom(" + getFROM() + "). " + e1.getMessage());
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        log.error("Failed to send email!", e);
    }
}

From source file:org.meerkat.network.MailManager.java

/**
 * testEmailSettingsFromWebService// w  w w.j  av  a 2s  . c  o m
 * @param from
 * @param to
 * @param smtpServer
 * @param smtpPort
 * @param smtpSecurity
 * @param smtpUser
 * @param smtpPassword
 * @return
 */
public final String sendTestEmailSettingsFromWebService(String from, String to, String smtpServer,
        String smtpPort, String smtpSecurity, String smtpUser, String smtpPassword) {
    String resultString = "OK";
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtpServer);
    email.setSmtpPort(Integer.valueOf(smtpPort));
    email.setSubject(testSubject);
    try {
        email.setHtmlMsg(testMessage);
    } catch (EmailException e2) {
        resultString = e2.getMessage();
        return resultString;
    }

    // SMTP security
    if (smtpSecurity.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (smtpSecurity.equalsIgnoreCase("SSLTLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(smtpPort));
    }
    email.setAuthentication(smtpUser, smtpPassword);

    try {
        String[] toList = to.split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        resultString = "TO: " + e1.getMessage();
        return resultString;
    }

    try {
        email.setFrom(from);
    } catch (EmailException e1) {
        resultString = "FROM: " + e1.getMessage();
        return resultString;
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        resultString = e.getMessage();
        return resultString;
    }

    return resultString;
}

From source file:org.opencron.server.service.NoticeService.java

public void sendMessage(List<User> users, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(false);/*  w  w  w  .j  av a2  s  .c o  m*/
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;

    Config config = configService.getSysConfig();
    try {
        log.setType(Opencron.MsgType.EMAIL.getValue());
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("opencron");
        email.setHtmlMsg(msgToHtml(content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));
            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);
            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(Opencron.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        for (User user : users) {
            //??
            log.setUserId(user.getUserId());
            log.setReceiver(user.getUserName());
            homeService.saveLog(log);
        }
    }

}

From source file:org.oscarehr.oscar_apps.util.Log4JGmailExecutorTask.java

private void sendEmail() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtpServer);/*from   w w  w .j  av a2 s . co m*/
    if (smtpUser != null && smtpPassword != null)
        email.setAuthentication(smtpUser, smtpPassword);

    if (smtpSslPort != null) {
        email.setSSL(true);
        email.setSslSmtpPort(smtpSslPort);
    }

    Session session = email.getMailSession();
    Properties properties = session.getProperties();
    properties.setProperty("mail.smtp.connectiontimeout", "20000");
    properties.setProperty("mail.smtp.timeout", "20000");

    email.addTo(recipientEmailAddress, recipientEmailAddress);
    email.setFrom(smtpUser, smtpUser);

    email.setSubject(subject);
    email.setHtmlMsg(contents);
    email.setTextMsg(contents);
    email.send();
}

From source file:org.oscarehr.util.EmailUtils.java

/**
 * This method will return an HtmlEmail object populated with 
 * the values passed in, ignoring the parameters in the configuration file.
 *///from  w  w w .  j av a 2s . c o  m
public static HtmlEmail getHtmlEmail(String smtpServer, String smtpPort, String smtpUser, String smtpPassword,
        String connectionSecurity) throws EmailException {
    logger.debug("smtpServer=" + smtpServer + ", smtpSslPort=" + smtpPort + ", smtpUser=" + smtpUser
            + ", smtpPassword=" + smtpPassword + ",connectionSecurity=" + connectionSecurity);

    HtmlEmail email = null;

    if (RECIPIENT_OVERRIDE_KEY != null || printInsteadOfSend)
        email = new HtmlEmailWrapper();
    else
        email = new HtmlEmail();

    email.setHostName(smtpServer);

    if (smtpUser != null && smtpPassword != null)
        email.setAuthentication(smtpUser, smtpPassword);

    Session session = email.getMailSession();

    if (connectionSecurity != null) {
        if (connectionSecurity.equals(CONNECTION_SECURITY_STARTTLS)) {
            session.getProperties().setProperty(Email.MAIL_TRANSPORT_TLS, "true");
            email.setTLS(true);
        } else if (connectionSecurity.equals(CONNECTION_SECURITY_SSL)) {
            email.setSSL(true);
        }
    }

    if (smtpPort != null) {
        email.setSslSmtpPort(smtpPort);
    }

    Properties properties = session.getProperties();
    properties.setProperty("mail.smtp.connectiontimeout", "20000");
    properties.setProperty("mail.smtp.timeout", "20000");

    return (email);
}