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

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

Introduction

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

Prototype

public Session getMailSession() throws EmailException 

Source Link

Document

Determines the mail session used when sending this Email, creating the Session if necessary.

Usage

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImpl.java

private void initEmailInfo(Email email) throws EmailException {
    email.setMailSession(mailSession);/*from  w  ww  .ja  v a  2  s  .  c o  m*/

    String smtpPort = email.getMailSession().getProperty(Email.MAIL_PORT);

    email.setFrom(senderEmail, senderName);
    if (StringUtils.isNumeric(smtpPort) && Integer.valueOf(smtpPort) > 0) {
        email.setSmtpPort(Integer.valueOf(smtpPort));
    }
}

From source file:com.kylinolap.job.tools.MailService.java

public void sendMail(List<String> receivers, String subject, String content) throws IOException {

    Email email = new HtmlEmail();
    email.setHostName(host);//from   w w  w  .  j a v a 2s .  c  o  m
    email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        ((HtmlEmail) email).setHtmlMsg(content);
        email.send();
        email.getMailSession();

        System.out.println("!!");
    } catch (EmailException e) {
        e.printStackTrace();
    }
}

From source file:com.kylinolap.common.util.MailService.java

/**
 * /*w  w w.j a  v  a2 s .  c o m*/
 * @param receivers
 * @param subject
 * @param content
 * @return true or false indicating whether the email was delivered successfully
 * @throws IOException
 */
public boolean sendMail(List<String> receivers, String subject, String content) throws IOException {

    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'mail.enabled=true' in kylin.properties");
        return false;
    }

    Email email = new HtmlEmail();
    email.setHostName(host);
    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }

    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        ((HtmlEmail) email).setHtmlMsg(content);
        email.send();
        email.getMailSession();

    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        return false;
    }

    return true;
}

From source file:com.gst.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService
            .getSMTPCredentials();/*from  w  w  w .ja v  a2 s.c o  m*/
    final String authuserName = smtpCredentialsData.getUsername();

    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        }
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("Welcome ")
                .append(emailDetail.getContactName()).append(" to ").append(emailDetail.getOrganisationName());

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on Mifos.\n")
                .append("You can login using the following credentials:\nusername: ")
                .append(emailDetail.getUsername()).append("\n").append("password: ").append(unencodedPassword)
                .append("\n")
                .append("You must change this password upon first log in using Uppercase, Lowercase, number and character.\n")
                .append("Thank you and welcome to the organisation.");

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:com.mirth.connect.server.util.ServerSMTPConnection.java

public void send(String toList, String ccList, String from, String subject, String body, String charset)
        throws EmailException {
    Email email = new SimpleEmail();

    // Set the charset if it was specified. Otherwise use the system's default.
    if (StringUtils.isNotBlank(charset)) {
        email.setCharset(charset);/*from   w  ww. j av  a2s .  c o  m*/
    }

    email.setHostName(host);
    email.setSmtpPort(Integer.parseInt(port));
    email.setSocketConnectionTimeout(socketTimeout);
    email.setDebug(true);

    if (useAuthentication) {
        email.setAuthentication(username, password);
    }

    if (StringUtils.equalsIgnoreCase(secure, "TLS")) {
        email.setStartTLSEnabled(true);
    } else if (StringUtils.equalsIgnoreCase(secure, "SSL")) {
        email.setSSLOnConnect(true);
        email.setSslSmtpPort(port);
    }

    // These have to be set after the authenticator, so that a new mail session isn't created
    ConfigurationController configurationController = ControllerFactory.getFactory()
            .createConfigurationController();
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.protocols", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols()), ' '));
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.ciphersuites", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites()), ' '));

    for (String to : StringUtils.split(toList, ",")) {
        email.addTo(to);
    }

    if (StringUtils.isNotEmpty(ccList)) {
        for (String cc : StringUtils.split(ccList, ",")) {
            email.addCc(cc);
        }
    }

    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(body);
    email.send();
}

From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties;
    String responseData = null;/*from   w w  w  . j  ava  2 s  . c  o  m*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;

    String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo()
            + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":"
            + smtpDispatcherProperties.getSmtpPort();
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING, info));

    try {
        Email email = null;

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

        email.setCharset(charsetEncoding);

        email.setHostName(smtpDispatcherProperties.getSmtpHost());

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

        try {
            int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout());
            email.setSocketTimeout(timeout);
            email.setSocketConnectionTimeout(timeout);
        } catch (NumberFormatException e) {
            // Don't set if the value is invalid
        }

        // This has to be set before the authenticator because a session shouldn't be created yet
        configuration.configureEncryption(connectorProperties, email);

        if (smtpDispatcherProperties.isAuthentication()) {
            email.setAuthentication(smtpDispatcherProperties.getUsername(),
                    smtpDispatcherProperties.getPassword());
        }

        Properties mailProperties = email.getMailSession().getProperties();
        // These have to be set after the authenticator, so that a new mail session isn't created
        configuration.configureMailProperties(mailProperties);

        if (smtpDispatcherProperties.isOverrideLocalBinding()) {
            mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress());
            mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort());
        }
        /*
         * 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 : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) {
            email.addTo(to);
        }

        // Currently unused
        for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) {
            email.addCc(cc);
        }

        // Currently unused
        for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) {
            email.addBcc(bcc);
        }

        // Currently unused
        for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) {
            email.addReplyTo(replyTo);
        }

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

        email.setFrom(smtpDispatcherProperties.getFrom());
        email.setSubject(smtpDispatcherProperties.getSubject());

        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();

        String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(),
                connectorMessage);

        if (StringUtils.isNotEmpty(body)) {
            if (smtpDispatcherProperties.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 : smtpDispatcherProperties.getAttachments()) {
            String name = attachment.getName();
            String mimeType = attachment.getMimeType();
            String content = attachment.getContent();

            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 = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else if ("application/xml".equalsIgnoreCase(mimeType)
                    || StringUtils.startsWith(mimeType, "text/")) {
                logger.debug("text or XML MIME type detected for attachment \"" + name + "\"");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding,
                        false);
            } else {
                logger.debug("binary MIME type detected for attachment \"" + name
                        + "\", performing Base64 decoding");
                bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true);
            }

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

        /*
         * From the Commons Email JavaDoc: send returns
         * "the message id of the underlying MimeMessage".
         */
        responseData = email.send();
        responseStatus = Status.SENT;
        responseStatusMessage = "Email sent successfully.";
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error sending email message", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error sending email message", e);

        // TODO: Exception handling
        //            connector.handleException(new Exception(e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError);
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public ConnectionTestResponse sendTestEmail(Properties properties) throws Exception {
    String portString = properties.getProperty("port");
    String encryption = properties.getProperty("encryption");
    String host = properties.getProperty("host");
    String timeoutString = properties.getProperty("timeout");
    Boolean authentication = Boolean.parseBoolean(properties.getProperty("authentication"));
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String to = properties.getProperty("toAddress");
    String from = properties.getProperty("fromAddress");

    int port = -1;
    try {//from  w  w  w.  j av a2 s.  c  o  m
        port = Integer.parseInt(portString);
    } catch (NumberFormatException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                "Invalid port: \"" + portString + "\"");
    }

    Email email = new SimpleEmail();
    email.setDebug(true);
    email.setHostName(host);
    email.setSmtpPort(port);

    try {
        int timeout = Integer.parseInt(timeoutString);
        email.setSocketTimeout(timeout);
        email.setSocketConnectionTimeout(timeout);
    } catch (NumberFormatException e) {
        // Don't set if the value is invalid
    }

    if ("SSL".equalsIgnoreCase(encryption)) {
        email.setSSLOnConnect(true);
        email.setSslSmtpPort(portString);
    } else if ("TLS".equalsIgnoreCase(encryption)) {
        email.setStartTLSEnabled(true);
    }

    if (authentication) {
        email.setAuthentication(username, password);
    }

    // These have to be set after the authenticator, so that a new mail session isn't created
    ConfigurationController configurationController = ControllerFactory.getFactory()
            .createConfigurationController();
    String protocols = properties.getProperty("protocols", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols()), ' '));
    String cipherSuites = properties.getProperty("cipherSuites", StringUtils.join(
            MirthSSLUtil.getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites()), ' '));
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.protocols", protocols);
    email.getMailSession().getProperties().setProperty("mail.smtp.ssl.ciphersuites", cipherSuites);

    SSLSocketFactory socketFactory = (SSLSocketFactory) properties.get("socketFactory");
    if (socketFactory != null) {
        email.getMailSession().getProperties().put("mail.smtp.ssl.socketFactory", socketFactory);
        if ("SSL".equalsIgnoreCase(encryption)) {
            email.getMailSession().getProperties().put("mail.smtp.socketFactory", socketFactory);
        }
    }

    email.setSubject("Mirth Connect Test Email");

    try {
        for (String toAddress : StringUtils.split(to, ",")) {
            email.addTo(toAddress);
        }

        email.setFrom(from);
        email.setMsg(
                "Receipt of this email confirms that mail originating from this Mirth Connect Server is capable of reaching its intended destination.\n\nSMTP Configuration:\n- Host: "
                        + host + "\n- Port: " + port);

        email.send();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Sucessfully sent test email to: " + to);
    } catch (EmailException e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, e.getMessage());
    }
}

From source file:org.apache.fineract.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService
            .getSMTPCredentials();//ww w  .  j ava 2 s  . c  om
    final String authuserName = smtpCredentialsData.getUsername();

    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        }
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("Fineract Prototype Demo: ")
                .append(emailDetail.getContactName()).append(" user account creation.");

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on Fineract Prototype Demo.")
                .append("You can login using the following credentials: username: ")
                .append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword);

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.apache.kylin.common.util.MailService.java

/**
 * @param receivers//from   ww  w .j  a va  2s .  c om
 * @param subject
 * @param content
 * @return true or false indicating whether the email was delivered successfully
 * @throws IOException
 */
public boolean sendMail(List<String> receivers, String subject, String content, boolean isHtmlMsg) {

    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'kylin.job.notification-enabled=true' in kylin.properties");
        return false;
    }

    Email email = new HtmlEmail();
    email.setHostName(host);
    email.setStartTLSEnabled(starttlsEnabled);
    if (starttlsEnabled) {
        email.setSslSmtpPort(port);
    } else {
        email.setSmtpPort(Integer.valueOf(port));
    }

    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }

    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        if (isHtmlMsg) {
            ((HtmlEmail) email).setHtmlMsg(content);
        } else {
            ((HtmlEmail) email).setTextMsg(content);
        }
        email.send();
        email.getMailSession();

    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        return false;
    }

    return true;
}

From source file:org.apache.wookie.helpers.WidgetKeyManager.java

/**
 * Send email./*w  ww .j  ava2 s .com*/
 * 
 * @param mailserver - the SMTP mail server address
 * @param from
 * @param to
 * @param message
 * @throws Exception
 */
private static void sendEmail(String mailserver, int port, String from, String to, String message,
        String username, String password) throws EmailException {
    Email email = new SimpleEmail();
    email.setDebug(false); // true if you want to debug
    email.setHostName(mailserver);
    if (username != null) {
        email.setAuthentication(username, password);
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
    }
    email.setFrom(from, "Wookie Server");
    email.setSubject("Wookie API Key");
    email.setMsg(message);
    email.addTo(to);
    email.send();
}