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

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

Introduction

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

Prototype

public Email setStartTLSRequired(final boolean startTlsRequired) 

Source Link

Document

Set or disable the required STARTTLS encryption.

Usage

From source file:gribbit.util.SendEmail.java

/** Send an email. Don't forget to use fully-qualified URLs in the message body. */
public static void sendEmail(final String toName, final String to, final String subject,
        final DataModel message, final String messagePlainText) {
    // Queue sending of email in a new thread
    GribbitServer.vertx.executeBlocking(future -> {
        if (GribbitProperties.SMTP_SERVER == null || GribbitProperties.SEND_EMAIL_ADDRESS == null
                || GribbitProperties.SEND_EMAIL_PASSWORD == null || GribbitProperties.SEND_EMAIL_ADDRESS == null
                || GribbitProperties.SEND_EMAIL_NAME == null) {
            throw new RuntimeException("SMTP is not fully configured in the properties file");
        }//from w  ww.j av  a 2 s .c o m

        String fullEmailAddr = "\"" + toName + "\" <" + to + ">";
        try {
            HtmlEmail email = new ImageHtmlEmail();
            email.setDebug(false);

            email.setHostName(GribbitProperties.SMTP_SERVER);
            email.setSmtpPort(GribbitProperties.SMTP_PORT);
            email.setAuthenticator(new DefaultAuthenticator(GribbitProperties.SEND_EMAIL_ADDRESS,
                    GribbitProperties.SEND_EMAIL_PASSWORD));
            email.setStartTLSRequired(true);

            email.addTo(to, toName);
            email.setFrom(GribbitProperties.SEND_EMAIL_ADDRESS, GribbitProperties.SEND_EMAIL_NAME);
            email.setSubject(subject);
            email.setHtmlMsg(message.toString());
            email.setTextMsg(messagePlainText);

            email.send();

            Log.info("Sent email to " + fullEmailAddr + " : " + subject);

        } catch (EmailException e) {
            Log.exception("Failure while trying to send email to " + fullEmailAddr + " : " + subject, e);
        }
        future.complete();

    }, res -> {
        if (res.failed()) {
            Log.error("Exception while trying to send email");
        }
    });
}

From source file:com.github.robozonky.notifications.EmailHandler.java

private HtmlEmail createNewEmail(final SessionInfo session) throws EmailException {
    final HtmlEmail email = new HtmlEmail();
    email.setCharset(Defaults.CHARSET.displayName()); // otherwise the e-mail contents are mangled
    email.setHostName(getSmtpHostname());
    email.setSmtpPort(getSmtpPort());//w w w. j  a  v  a 2 s.co m
    email.setStartTLSRequired(isStartTlsRequired());
    email.setSSLOnConnect(isSslOnConnectRequired());
    if (isAuthenticationRequired()) {
        final String username = getSmtpUsername();
        LOGGER.debug("Will contact SMTP server as '{}'.", username);
        email.setAuthentication(getSmtpUsername(), getSmtpPassword());
    } else {
        LOGGER.debug("Will contact SMTP server anonymously.");
    }
    email.setFrom(getSender(), session.getName());
    email.addTo(getRecipient());
    return email;
}

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;//ww w  .j a  v a2 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);
    }

}