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

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

Introduction

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

Prototype

public void setSocketTimeout(final int socketTimeout) 

Source Link

Document

Set the socket I/O timeout value in milliseconds.

Usage

From source file:com.turn.sorcerer.util.email.Emailer.java

private void sendEmail() throws EmailException, UnknownHostException {

    List<String> addresses = Lists
            .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(ADMIN_EMAIL.getAdmins()));
    logger.info("Sending email to {}", addresses.toString());

    Email email = new HtmlEmail();
    email.setHostName(ADMIN_EMAIL.getHost());
    email.setSocketTimeout(30000); // 30 seconds
    email.setSocketConnectionTimeout(30000); // 30 seconds
    for (String address : addresses) {
        email.addTo(address);/*from   ww w  .  jav a  2  s. co  m*/
    }
    email.setFrom(
            SorcererInjector.get().getModule().getName() + "@" + InetAddress.getLocalHost().getHostName());
    email.setSubject(title);
    email.setMsg(body);
    email.send();

}

From source file:com.pronoiahealth.olhie.server.services.MailSendingService.java

/**
 * Sends a password reset email to the email address provided
 * //from  ww  w  .j  a v a  2 s.  c o  m
 * @param toEmail
 * @param newPwd
 * @throws Exception
 */
public void sendPwdResetMailFromApp(String toEmail, String newPwd) throws Exception {
    Email email = new SimpleEmail();
    email.setSmtpPort(Integer.parseInt(smtpPort));
    email.setAuthenticator(new DefaultAuthenticator(fromAddress, fromPwd));
    email.setDebug(Boolean.parseBoolean(debugEnabled));
    email.setHostName(smtpSever);
    email.setFrom(fromAddress);
    email.setSubject("Reset Olhie Password");
    email.setMsg("You have requested that your password be reset. Your new Olhie password is " + newPwd);
    email.addTo(toEmail);
    email.setTLS(Boolean.parseBoolean(tlsEnabled));
    email.setSocketTimeout(10000);
    email.setSocketConnectionTimeout(12000);
    email.send();
}

From source file:com.pronoiahealth.olhie.server.services.MailSendingService.java

/**
 * Author Request email that goes to the olhie administrator
 * /*from w ww .j a v a2 s  .com*/
 * @param toEmail
 * @param userId
 * @param firstName
 * @param lastName
 * @param regId
 * @throws Exception
 */
public void sendRequestAuthorMailFromApp(String toEmail, String userId, String firstName, String lastName,
        String regId) throws Exception {
    Email email = new SimpleEmail();
    email.setSmtpPort(Integer.parseInt(smtpPort));
    email.setAuthenticator(new DefaultAuthenticator(fromAddress, fromPwd));
    email.setDebug(Boolean.parseBoolean(debugEnabled));
    email.setHostName(smtpSever);
    email.setFrom(fromAddress);
    email.setSubject("Author Request");
    email.setMsg("User Id: " + userId + " Name: " + firstName + " " + lastName + " Registration Id: " + regId);
    email.addTo(toEmail);
    email.setTLS(Boolean.parseBoolean(tlsEnabled));
    email.setSocketTimeout(10000);
    email.setSocketConnectionTimeout(12000);
    email.send();
}

From source file:com.pronoiahealth.olhie.server.services.MailSendingService.java

/**
 * @param toEmail// ww  w.j a va  2 s .  c om
 * @param userId
 * @param firstName
 * @param lastName
 * @param eventId
 * @param details
 * @throws Exception
 */
public void sendRequestMailForCalendarEventFromApp(String toEmail, String userId, String firstName,
        String lastName, String eventId, String details) throws Exception {
    Email email = new SimpleEmail();
    email.setSmtpPort(Integer.parseInt(smtpPort));
    email.setAuthenticator(new DefaultAuthenticator(fromAddress, fromPwd));
    email.setDebug(Boolean.parseBoolean(debugEnabled));
    email.setHostName(smtpSever);
    email.setFrom(fromAddress);
    email.setSubject("Calendar Event Request");
    email.setMsg("User Id: " + userId + " Name: " + firstName + " " + lastName + " Event Id: " + eventId + "\n"
            + details);
    email.addTo(toEmail);
    email.setTLS(Boolean.parseBoolean(tlsEnabled));
    email.setSocketTimeout(10000);
    email.setSocketConnectionTimeout(12000);
    email.send();
}

From source file:com.qwazr.connectors.EmailConnector.java

public void sendEmail(Email email) throws EmailException {
    email.setHostName(hostname);// w w w. j a  v  a 2s . c  o m
    if (ssl != null)
        email.setSSLOnConnect(ssl);
    if (start_tls_enabled != null)
        email.setStartTLSEnabled(start_tls_enabled);
    if (start_tls_required != null)
        email.setStartTLSRequired(start_tls_required);
    if (port != null)
        email.setSmtpPort(port);
    if (username != null)
        email.setAuthentication(username, password);
    if (connection_timeout != null)
        email.setSocketConnectionTimeout(connection_timeout);
    if (timeout != null)
        email.setSocketTimeout(timeout);
    email.send();
}

From source file:com.qwazr.library.email.EmailConnector.java

public void sendEmail(final Email email) throws EmailException {
    email.setHostName(hostname);//from w ww. ja v a2s  .c  o m
    if (ssl != null)
        email.setSSLOnConnect(ssl);
    if (start_tls_enabled != null)
        email.setStartTLSEnabled(start_tls_enabled);
    if (start_tls_required != null)
        email.setStartTLSRequired(start_tls_required);
    if (port != null)
        email.setSmtpPort(port);
    if (username != null)
        email.setAuthentication(username, password);
    if (connection_timeout != null)
        email.setSocketConnectionTimeout(connection_timeout);
    if (timeout != null)
        email.setSocketTimeout(timeout);
    email.send();
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImpl.java

private Email getEmail(final MailTemplate mailTemplate, final Class<? extends Email> mailType,
        final Map<String, String> params) throws EmailException, MessagingException, IOException {

    final Email email = mailTemplate.getEmail(StrLookup.mapLookup(params), mailType);

    if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)
            && params.containsKey(EmailServiceConstants.SENDER_NAME)) {

        email.setFrom(params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS),
                params.get(EmailServiceConstants.SENDER_NAME));

    } else if (params.containsKey(EmailServiceConstants.SENDER_EMAIL_ADDRESS)) {
        email.setFrom(params.get(EmailServiceConstants.SENDER_EMAIL_ADDRESS));
    }//from w ww .j ava2  s. com
    if (connectTimeout > 0) {
        email.setSocketConnectionTimeout(connectTimeout);
    }
    if (soTimeout > 0) {
        email.setSocketTimeout(soTimeout);
    }

    // #1008 setting the subject via the setSubject(..) parameter.
    if (params.containsKey(EmailServiceConstants.SUBJECT)) {
        email.setSubject(params.get(EmailServiceConstants.SUBJECT));
    }

    return email;
}

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 ww.  j av a2s  . co 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:adams.core.net.SimpleApacheSendEmail.java

/**
 * Sends an email./* ww w.j a  v  a  2s.co  m*/
 *
 * @param email   the email to send
 * @return      true if successfully sent
 * @throws Exception   in case of invalid internet addresses or messaging problem
 */
@Override
public boolean sendMail(Email email) throws Exception {
    org.apache.commons.mail.Email mail;
    String id;
    MultiPartEmail mpemail;
    EmailAttachment attachment;

    if (email.getAttachments().length > 0) {
        mail = new MultiPartEmail();
        mpemail = (MultiPartEmail) mail;
        for (File file : email.getAttachments()) {
            attachment = new EmailAttachment();
            attachment.setPath(file.getAbsolutePath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(file.getName());
            mpemail.attach(attachment);
        }
    } else {
        mail = new SimpleEmail();
    }
    mail.setFrom(email.getFrom().getValue());
    for (EmailAddress address : email.getTo())
        mail.addTo(address.getValue());
    for (EmailAddress address : email.getCC())
        mail.addCc(address.getValue());
    for (EmailAddress address : email.getBCC())
        mail.addBcc(address.getValue());
    mail.setSubject(email.getSubject());
    mail.setMsg(email.getBody());
    mail.setHostName(m_Server);
    mail.setSmtpPort(m_Port);
    mail.setStartTLSEnabled(m_UseTLS);
    mail.setSSLOnConnect(m_UseSSL);
    if (m_RequiresAuth)
        mail.setAuthentication(m_User, m_Password.getValue());
    mail.setSocketTimeout(m_Timeout);
    try {
        id = mail.send();
        if (isLoggingEnabled())
            getLogger().info("Message sent: " + id);
    } catch (Exception e) {
        getLogger().log(Level.SEVERE, "Failed to send email: " + mail, e);
        return false;
    }

    return true;
}

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 {//w ww .  j ava  2  s.  c  om
        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());
    }
}