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

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

Introduction

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

Prototype

public Email addTo(final String... emails) throws EmailException 

Source Link

Document

Add a list of TO recipients to the email.

Usage

From source file:com.pkrete.locationservice.endpoint.mailer.impl.EmailServiceImpl.java

/**
 * Sends the given EmailMessage to the recipients defined in the message.
 * Returns true if and only if the message was successfully sent to all the
 * recipients; otherwise false./* w  w w  . j  ava2 s  .c  o m*/
 *
 * @param message email message to be sent
 * @return true if and only if the message was successfully sent to all the
 * recipients; otherwise false
 */
@Override
public boolean send(EmailMessage message) {
    if (message == null) {
        logger.warn("Message cannot be null.");
        return false;
    }
    logger.debug("Create new \"{}\" email message.", message.getType().toString());

    if (message.getRecipients().isEmpty()) {
        logger.info("No recipients defined. Nothing to do -> exit.");
        return false;
    }
    Email email = new SimpleEmail();
    email.setHostName(PropertiesUtil.getProperty("mail.host"));
    email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port")));
    email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"),
            PropertiesUtil.getProperty("mail.password")));
    email.setTLS(true);
    try {
        // Set from address
        email.setFrom(message.getFrom());
        // Set subject
        email.setSubject(message.getSubject());

        // Build message body
        StringBuilder body = new StringBuilder();
        if (!message.getHeader().isEmpty()) {
            body.append(message.getHeader()).append("\n\n");
        }
        if (!message.getMessage().isEmpty()) {
            body.append(message.getMessage()).append("\n\n");
        }
        if (!message.getFooter().isEmpty()) {
            body.append(message.getFooter()).append("\n\n");
        }
        if (!message.getSignature().isEmpty()) {
            body.append(message.getSignature()).append("\n\n");
        }

        // Set message contents
        email.setMsg(body.toString());

        // Add message receivers
        for (String recipient : message.getRecipients()) {
            logger.info("Add recipient \"{}\".", recipient);
            email.addTo(recipient);
        }

        // Send message
        email.send();

        logger.info("Email was succesfully sent to {} recipients.", message.getRecipients().size());
    } catch (Exception e) {
        logger.error("Failed to send \"{}\" email message.", message.getType().toString());
        logger.error(e.getMessage());
        return false;
    }
    return true;
}

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 ww  w . j ava2s  .  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.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;//from  w  w  w  .  j  a  va  2 s.co m
    }

    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:FacultyAdvisement.SignupBean.java

public String validateSignUp(ArrayList<Course> list, Appointment appointment)
        throws SQLException, IOException, EmailException {

    if (this.desiredCoureses == null || this.desiredCoureses.size() < 1) {
        FacesContext.getCurrentInstance().addMessage("desiredCourses:Submit",
                new FacesMessage(FacesMessage.SEVERITY_FATAL,
                        "Please select some courses before confirming an appointment.", null));

    }/*w w  w.  j a va 2s .  co m*/
    for (int i = 0; i < list.size(); i++) {
        if (!this.checkRequsites(CourseRepository.readCourseWithRequisites(ds, list.get(i)))) {
            return null;

        }
    }

    try {
        DesiredCourseRepository.deleteFromAppointment(ds, this.appointment.aID);
    } catch (SQLException ex) {
        Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    DesiredCourseRepository.createDesiredCourses(ds, desiredCoureses, Long.toString(appointment.aID));

    if (!this.edit) {
        try {
            Email email = new HtmlEmail();
            email.setHostName("smtp.googlemail.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("uco.faculty.advisement", "!@#$1234"));
            email.setSSLOnConnect(true);
            email.setFrom("uco.faculty.advisement@gmail.com");
            email.setSubject("UCO Faculty Advisement Appointmen Confirmation");

            StringBuilder table = new StringBuilder();
            table.append("<style>" + "td" + "{border-left:1px solid black;" + "border-top:1px solid black;}"
                    + "table" + "{border-right:1px solid black;" + "border-bottom:1px solid black;}"
                    + "</style>");
            table.append(
                    "<table><tr><td  width=\"350\">Course Name</td><td  width=\"350\">Course Subject</td><td  width=\"350\">Course Number</td><td  width=\"350\">Course Credits</td></tr> </table>");
            for (int i = 0; i < this.desiredCoureses.size(); i++) {
                table.append("<tr><td   width=\"350\">" + this.desiredCoureses.get(i).getName() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getSubject() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getNumber() + "</td>"
                        + "<td   width=\"350\">" + this.desiredCoureses.get(i).getCredits() + "</td></tr>"

                );

            }

            email.setMsg("<p>Your appointment with your faculty advisor is at " + appointment.datetime + " on "
                    + appointment.date + " . </p>" + "<p align=\"center\">Desired Courses</p>"
                    + table.toString() + "<p align=\"center\">UCO Faculty Advisement</p></font>"

            );
            email.addTo(username);
            email.send();
        } catch (EmailException ex) {
            Logger.getLogger(VerificationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "/customerFolder/profile.xhtml";
}

From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java

/**
 * Email//www .ja v  a2  s .c  om
 * 
 * @param mail
 * @return
 * @throws Exception
 */
protected Email getEmail(MsunMail mail) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("send mail use smth : " + hostName);
    }
    // set env for logger
    mail.getEnvironment().setHostName(hostName);
    mail.getEnvironment().setUser(user);
    mail.getEnvironment().setPassword(password);

    Email email = null;

    if (!StringUtils.isEmpty(mail.getHtmlMessage())) {
        email = makeHtmlEmail(mail, mail.getCharset());
    } else {
        if ((mail.getAttachment() == null || mail.getAttachment().length == 0)
                && mail.getAttachments().isEmpty()) {
            email = makeSimpleEmail(mail, mail.getCharset());
        } else {
            email = makeSimpleEmailWithAttachment(mail, mail.getCharset());
        }
    }

    if (auth) {
        // email.setAuthenticator(new MyAuthenticator(user, password));
        email.setAuthentication(user, password);
    }
    email.setHostName(hostName);

    if (mail.getTo() == null) {
        mail.setTo(defaultTo.split(";"));
    }

    if (StringUtils.isEmpty(mail.getFrom())) {
        mail.setFrom(defaultFrom);
    }

    email.setFrom(mail.getFrom(), mail.getFromName());

    List<String> unqualifiedReceiver = mail.getUnqualifiedReceiver();
    String[] mailTo = mail.getTo();
    String[] mailCc = mail.getCc();
    String[] mailBcc = mail.getBcc();
    if (unqualifiedReceiver != null && unqualifiedReceiver.size() > 0) {
        if (mailTo != null && mailTo.length > 0) {
            mailTo = filterReceiver(mailTo, unqualifiedReceiver);
        }
        if (mailCc != null && mailCc.length > 0) {
            mailCc = filterReceiver(mailCc, unqualifiedReceiver);
        }
        if (mailBcc != null && mailBcc.length > 0) {
            mailBcc = filterReceiver(mailBcc, unqualifiedReceiver);
        }
    }

    if (mailTo == null && mailCc == null && mailBcc == null) {
        throw new MessageSerivceException("?????");
    }

    int count = 0;

    if (mailTo != null) {
        count += mailTo.length;
        for (String to : mailTo) {
            email.addTo(to);
        }
    }

    if (mailCc != null) {
        count += mailCc.length;
        for (String cc : mailCc) {
            email.addCc(cc);
        }
    }
    if (mailBcc != null) {
        count += mailBcc.length;
        for (String bcc : mailBcc) {
            email.addBcc(bcc);
        }
    }

    if (count < 1) {
        throw new MessageSerivceException("?????");
    }

    if (!StringUtils.isEmpty(mail.getReplyTo())) {
        email.addReplyTo(mail.getReplyTo());
    }

    if (mail.getHeaders() != null) {
        for (Iterator<String> iter = mail.getHeaders().keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            email.addHeader(key, (String) mail.getHeaders().get(key));
        }
    }

    email.setSubject(mail.getSubject());

    // 
    if (email instanceof MultiPartEmail) {
        MultiPartEmail multiEmail = (MultiPartEmail) email;

        if (mail.getAttachments().isEmpty()) {
            File[] fs = mail.getAttachment();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(fs[i].getAbsolutePath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setName(MimeUtility.encodeText(fs[i].getName()));// ???
                    multiEmail.attach(attachment);
                }
            }
        } else {
            for (MsunMailAttachment attachment : mail.getAttachments()) {
                DataSource ds = new ByteArrayDataSource(attachment.getData(), null);
                multiEmail.attach(ds, MimeUtility.encodeText(attachment.getName()), null);
            }
        }
    }
    return email;
}

From source file:JavaMail.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {/*  w w  w  .  ja  va2  s  . c o  m*/
        String from = jTextField1.getText();
        String to = jTextField2.getText();
        String subject = jTextField3.getText();
        String content = jTextArea1.getText();
        Email email = new SimpleEmail();
        String provi = prov.getSelectedItem().toString();
        if (provi.equals("Gmail")) {
            email.setHostName("smtp.gmail.com");
            email.setSmtpPort(465);
            serverlink = "smtp.gmail.com";
            serverport = 465;
        }
        if (provi.equals("Outlook")) {
            email.setHostName("smtp-mail.outlook.com");
            serverlink = "smtp-mail.outlook.com";
            email.setSmtpPort(25);
            serverport = 25;
        }
        if (provi.equals("Yahoo")) {
            email.setHostName("smtp.mail.yahoo.com");
            serverlink = "smtp.mail.yahoo.com";
            email.setSmtpPort(465);
            serverport = 465;
        }
        System.out.println("Initializing email sending sequence");
        System.out.println("Connecting to " + serverlink + " at port " + serverport);
        JPanel panel = new JPanel();
        JLabel label = new JLabel(
                "Enter the password of your email ID to connect with your Email provider." + "\n");
        JPasswordField pass = new JPasswordField(10);
        panel.add(label);
        panel.add(pass);
        String[] options = new String[] { "OK", "Cancel" };
        int option = JOptionPane.showOptionDialog(null, panel, "Enter Email ID Password", JOptionPane.NO_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
        if (option == 0) // pressing OK button
        {
            char[] password = pass.getPassword();
            emailpass = new String(password);
        }
        email.setAuthenticator(new DefaultAuthenticator(from, emailpass));
        email.setSSLOnConnect(true);
        if (email.isSSLOnConnect() == true) {
            System.out.println("This server requires SSL/TLS authentication.");
        }
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(content);
        email.addTo(to);
        email.send();
        JOptionPane.showMessageDialog(null, "Message sent successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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;//  w  w  w .  j a  v  a 2s.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.pkrete.locationservice.admin.mailer.impl.BasicEmailService.java

/**
 * Send an email to the given user when the user is created or the password
 * is modified./*from w  w w  .  j  a va  2  s  . co m*/
 *
 * @param user the receiver of the email
 */
@Override
public void send(UserFull user) {
    logger.info("Create new email message.");
    Email email = new SimpleEmail();
    email.setHostName(PropertiesUtil.getProperty("mail.host"));
    email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port")));
    email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"),
            PropertiesUtil.getProperty("mail.password")));
    email.setTLS(true);
    try {
        // Init variables
        String header = null;
        String msg = null;

        // Set from address
        email.setFrom(this.messageSource.getMessage("mail.from", null, null));

        // Set message arguments
        Object[] args = new Object[] { user.getUsername(), user.getPasswordUi() };

        // Set variables values
        if (user.getUpdated() == null) {
            // This is a new user
            if (logger.isDebugEnabled()) {
                logger.debug("The message is for a new user.");
            }
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.add", null, null));
            // Set message header
            header = this.messageSource.getMessage("mail.header.add", null, null);
            // Set message content
            msg = this.messageSource.getMessage("mail.message.add", args, null);
        } else {
            // This is an existing user
            logger.debug("The message is for an existing user.");
            // Set subject
            email.setSubject(this.messageSource.getMessage("mail.title.edit", null, null));
            // Get message header
            header = this.messageSource.getMessage("mail.header.edit", null, null);
            // Get message content
            msg = this.messageSource.getMessage("mail.message.edit", args, null);
        }

        // Get note
        String note = this.messageSource.getMessage("mail.note", null, null);
        // Get footer
        String footer = this.messageSource.getMessage("mail.footer", null, null);
        // Get signature
        String signature = this.messageSource.getMessage("mail.signature", null, null);

        // Build message body
        StringBuilder result = new StringBuilder();
        if (!header.isEmpty()) {
            result.append(header).append("\n\n");
        }
        if (!msg.isEmpty()) {
            result.append(msg).append("\n\n");
        }
        if (!note.isEmpty()) {
            result.append(note).append("\n\n");
        }
        if (!footer.isEmpty()) {
            result.append(footer).append("\n\n");
        }
        if (!signature.isEmpty()) {
            result.append(signature).append("\n\n");
        }
        // Set message contents
        email.setMsg(result.toString());
        // Set message receiver
        email.addTo(user.getEmail());
        // Send message
        email.send();
        logger.info("Email was sent to \"{}\".", user.getEmail());
    } catch (Exception e) {
        logger.error("Failed to send email to \"{}\".", user.getEmail());
        logger.error(e.getMessage(), e);
    }
}

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  ww .ja  v  a  2 s  .co  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:de.cosmocode.palava.services.mail.EmailFactory.java

@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */

    final Element root = document.getRootElement();

    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");

    final List<Element> attachments = root.getChildren("attachment");

    final Map<ContentType, String> available = new HashMap<ContentType, String>();

    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }/* w w w  .ja v a 2  s  .com*/
        available.put(messageType, element.getText());
    }

    final Email email;

    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);

        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }

        /**
         * Add html message
         */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }

        /**
         * Add plain text alternative
         */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }

        /**
         * Embedded binary data
         */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);

            final File file;

            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }

            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        /**
         * Attached binary data
         */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");

            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);

            if (!file.exists())
                file = new File(embed.getResourcePath(), path);

            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }

    final String subject = root.getChildText("subject");
    email.setSubject(subject);

    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);

    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }

    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }

    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }

    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }

    return email;
}