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

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

Introduction

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

Prototype

@Deprecated
public void setSSL(final boolean ssl) 

Source Link

Document

Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS).

Usage

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

/**
 * Send the actual email./*from   w  w  w. j  a v  a2  s . c o m*/
 * 
 * @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.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java

@Override
public void doDispatch(UMOEvent event) throws Exception {
    monitoringController.updateStatus(connector, connectorType, Event.BUSY);
    MessageObject mo = messageObjectController.getMessageObjectFromEvent(event);

    if (mo == null) {
        return;//w w  w  .  j a  va2 s .  com
    }

    try {
        Email email = null;

        if (connector.isHtml()) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(connector.getCharsetEncoding());

        email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo));

        try {
            email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        try {
            email.setSocketConnectionTimeout(
                    Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo)));
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        if ("SSL".equalsIgnoreCase(connector.getEncryption())) {
            email.setSSL(true);
        } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) {
            email.setTLS(true);
        }

        if (connector.isAuthentication()) {
            email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo),
                    replacer.replaceValues(connector.getPassword(), mo));
        }

        /*
         * NOTE: There seems to be a bug when calling setTo with a List
         * (throws a java.lang.ArrayStoreException), so we are using addTo
         * instead.
         */

        for (String to : replaceValuesAndSplit(connector.getTo(), mo)) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : replaceValuesAndSplit(connector.cc(), mo)) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) {
            email.addReplyTo(replyTo);
        }

        for (Entry<String, String> header : connector.getHeaders().entrySet()) {
            email.addHeader(replacer.replaceValues(header.getKey(), mo),
                    replacer.replaceValues(header.getValue(), mo));
        }

        email.setFrom(replacer.replaceValues(connector.getFrom(), mo));
        email.setSubject(replacer.replaceValues(connector.getSubject(), mo));

        String body = replacer.replaceValues(connector.getBody(), mo);

        if (connector.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        /*
         * If the MIME type for the attachment is missing, we display a
         * warning and set the content anyway. If the MIME type is of type
         * "text" or "application/xml", then we add the content. If it is
         * anything else, we assume it should be Base64 decoded first.
         */
        for (Attachment attachment : connector.getAttachments()) {
            String name = replacer.replaceValues(attachment.getName(), mo);
            String mimeType = replacer.replaceValues(attachment.getMimeType(), mo);
            String content = replacer.replaceValues(attachment.getContent(), mo);

            byte[] bytes;

            if (StringUtils.indexOf(mimeType, "/") < 0) {
                logger.warn("valid MIME type is missing for email attachment: \"" + name
                        + "\", using default of text/plain");
                attachment.setMimeType("text/plain");
                bytes = content.getBytes();
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = content.getBytes();
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = Base64.decodeBase64(content);
            }

            ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null);
        }

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        String response = email.send();
        messageObjectController.setSuccess(mo, response, null);
    } catch (EmailException e) {
        alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402,
                "Error sending email message.", e);
        messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null);
        connector.handleException(new Exception(e));
    } finally {
        monitoringController.updateStatus(connector, connectorType, Event.DONE);
    }
}

From source file:au.edu.ausstage.utils.EmailManager.java

/**
 * A method for sending a simple email message
 *
 * @param subject the subject of the message
 * @param message the text of the message
 *
 * @return true, if and only if, the email is successfully sent
 *///w ww  .j av  a2  s . c  o m
public boolean sendSimpleMessage(String subject, String message) {

    // check the input parameters
    if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false) {
        throw new IllegalArgumentException("The subject and message parameters cannot be null");
    }

    try {
        // define helper variables
        Email email = new SimpleEmail();

        // configure the instance of the email class
        email.setSmtpPort(options.getPortAsInt());

        // define authentication if required
        if (InputUtils.isValid(options.getUser()) == true) {
            email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword()));
        }

        // turn on / off debugging
        email.setDebug(DEBUG);

        // set the host name
        email.setHostName(options.getHost());

        // set the from email address
        email.setFrom(options.getFromAddress());

        // set the subject
        email.setSubject(subject);

        // set the message
        email.setMsg(message);

        // set the to address
        String[] addresses = options.getToAddress().split(":");

        for (int i = 0; i < addresses.length; i++) {
            email.addTo(addresses[i]);
        }

        // set the security options
        if (options.getTLS() == true) {
            email.setTLS(true);
        }

        if (options.getSSL() == true) {
            email.setSSL(true);
        }

        // send the email
        email.send();

    } catch (EmailException ex) {
        if (DEBUG) {
            System.err.println("ERROR: Sending of email failed.\n" + ex.toString());
        }

        return false;
    }
    return true;
}

From source file:org.activiti.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String mailSessionJndi = processEngineConfiguration.getMailSesionJndi();
    if (mailSessionJndi != null) {
        try {//from  ww  w . j a  v  a2s . com
            email.setMailSessionFromJNDI(mailSessionJndi);
        } catch (NamingException e) {
            throw new ActivitiException("Could not send email: Incorrect JNDI configuration", e);
        }
    } else {
        String host = processEngineConfiguration.getMailServerHost();
        if (host == null) {
            throw new ActivitiException("Could not send email: no SMTP host is configured");
        }
        email.setHostName(host);

        int port = processEngineConfiguration.getMailServerPort();
        email.setSmtpPort(port);

        email.setSSL(processEngineConfiguration.getMailServerUseSSL());
        email.setTLS(processEngineConfiguration.getMailServerUseTLS());

        String user = processEngineConfiguration.getMailServerUsername();
        String password = processEngineConfiguration.getMailServerPassword();
        if (user != null && password != null) {
            email.setAuthentication(user, password);
        }
    }
}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

private void setEmailStandardData(Email email) {
    email.setHostName(smtpServer);//from ww w .  j a  v  a2 s .  c  om

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

    email.setDebug(smtpDebug);
    email.setSmtpPort(smtpPort);
    email.setSSL(smtpSSL);
    email.setSslSmtpPort(String.valueOf(smtpSslPort));
    email.setTLS(smtpTLS);
}

From source file:org.killbill.billing.plugin.notification.email.EmailSender.java

private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email)
        throws EmailException {

    if (logOnly) {
        return;//from   w ww .j a v a 2s  . co  m
    }

    email.setSmtpPort(useSmtpPort);
    if (useSmtpAuth) {
        email.setAuthentication(smtpUserName, smtpUserPassword);
    }
    email.setHostName(smtpServerName);
    email.setFrom(from);

    email.setSubject(subject);

    if (to != null) {
        for (final String recipient : to) {
            email.addTo(recipient);
        }
    }

    if (cc != null) {
        for (final String recipient : cc) {
            email.addCc(recipient);
        }
    }

    email.setSSL(useSSL);

    logService.log(LogService.LOG_INFO,
            String.format("Sending email to %s, cc %s, subject %s", to, cc, subject));
    email.send();
}

From source file:org.killbill.billing.util.email.DefaultEmailSender.java

private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email)
        throws EmailApiException {
    try {//from  ww w.  j  ava 2s.co  m
        email.setSmtpPort(config.getSmtpPort());
        if (config.useSmtpAuth()) {
            email.setAuthentication(config.getSmtpUserName(), config.getSmtpPassword());
        }
        email.setHostName(config.getSmtpServerName());
        email.setFrom(config.getDefaultFrom());

        email.setSubject(subject);

        if (to != null) {
            for (final String recipient : to) {
                email.addTo(recipient);
            }
        }

        if (cc != null) {
            for (final String recipient : cc) {
                email.addCc(recipient);
            }
        }

        email.setSSL(config.useSSL());

        log.info("Sending email to='{}', cc='{}', subject='{}'", to, cc, subject);
        email.send();
    } catch (EmailException ee) {
        throw new EmailApiException(ee, ErrorCode.EMAIL_SENDING_FAILED);
    }
}

From source file:org.ms123.common.workflow.tasks.TaskMailExecutor.java

protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String host = processEngineConfiguration.getMailServerHost();
    if (host == null) {
        throw new RuntimeException("TaskMailExecutor:Could not send email: no SMTP host is configured");
    }/*from   w  w w.  j  a  va 2  s. com*/
    email.setHostName(host);

    int port = processEngineConfiguration.getMailServerPort();
    email.setSmtpPort(port);

    email.setSSL(processEngineConfiguration.getMailServerUseSSL());
    email.setTLS(processEngineConfiguration.getMailServerUseTLS());

    String user = processEngineConfiguration.getMailServerUsername();
    String password = processEngineConfiguration.getMailServerPassword();
    if (user != null && password != null) {
        email.setAuthentication(user, password);
    }
}

From source file:org.ms123.common.workflow.TaskSendExecutor.java

protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String host = processEngineConfiguration.getMailServerHost();
    if (host == null) {
        throw new RuntimeException("TaskSendExecutor:Could not send email: no SMTP host is configured");
    }// www. j  a  v a 2 s. co  m
    email.setHostName(host);

    int port = processEngineConfiguration.getMailServerPort();
    email.setSmtpPort(port);

    email.setSSL(processEngineConfiguration.getMailServerUseSSL());
    email.setTLS(processEngineConfiguration.getMailServerUseTLS());

    String user = processEngineConfiguration.getMailServerUsername();
    String password = processEngineConfiguration.getMailServerPassword();
    if (user != null && password != null) {
        email.setAuthentication(user, password);
    }
}

From source file:org.pepstock.jem.notify.engine.EmailNotifier.java

/**
 * This method sends an <code>Email</code>. <br>
 * It sets in the parameter <code>Email</code> the properties of the
 * parameter <code>JemEmail</code>: From User Email Address, From User Name,
 * subject, text, email destination addresses. <br>
 * It sets in the parameter <code>Email</code> the Email Server property and
 * the optional <code>SMTP</code> port, the properties that indicates if it
 * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and
 * password for <code>SMTP</code> server authentication if needed, the
 * optional bounce address, the subject, the text, and the recipients of the
 * email.// w  w w .  j a  v a  2  s . c  om
 * 
 * @param email the <code>JemEmail</code> with the properties of the email
 *            to be sent.
 * @param sendingEmail the real <code>Email</code> that will be sent.
 * @see JemEmail
 * @see Email
 * @throws SendMailException if an error occurs.
 */
private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException {
    try {
        sendingEmail.setHostName(this.emailServer);
        if (this.smtpPort != NO_SMTP_PORT) {
            sendingEmail.setSmtpPort(this.smtpPort);
        }
        sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName());
        if (email.hasSubject()) {
            sendingEmail.setSubject(email.getSubject());
        } else {
            // log no subject
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject");
        }
        if (email.hasText()) {
            sendingEmail.setMsg(email.getText());
        } else {
            // log no text message
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message");
        }
        sendingEmail.setTo(email.getAllToEmailAddresses());
        if (null != this.bounceAddress) {
            sendingEmail.setBounceAddress(this.bounceAddress);
        }
        sendingEmail.setSentDate(new Date());
        sendingEmail.setSSL(this.isSSL);
        sendingEmail.setTLS(this.isTLS);
        if (null != this.authenticationUserId && null != this.authenticationPassword) {
            sendingEmail.setAuthenticator(
                    new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword));
        }
        sendingEmail.send();
        LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email);
    } catch (EmailException eEx) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email);
        throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx);
    }
}