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

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

Introduction

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

Prototype

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

Source Link

Document

Add an array of CC recipients to the email.

Usage

From source file:com.day.cq.wcm.foundation.forms.impl.MailServlet.java

/**
 * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
 *///from   w ww.j a  va 2  s . c o m
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final MailService localService = this.mailService;
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        logger.debug("Received fake request!");
        response.setStatus(500);
        return;
    }
    final ResourceBundle resBundle = request.getResourceBundle(null);

    final ValueMap values = ResourceUtil.getValueMap(request.getResource());
    final String[] mailTo = values.get(MAILTO_PROPERTY, String[].class);
    int status = 200;
    if (mailTo == null || mailTo.length == 0 || mailTo[0].length() == 0) {
        // this is a sanity check
        logger.error(
                "The mailto configuration is missing in the form begin at " + request.getResource().getPath());

        status = 500;
    } else if (localService == null) {
        logger.error("The mail service is currently not available! Unable to send form mail.");

        status = 500;
    } else {
        try {
            final StringBuilder builder = new StringBuilder();
            builder.append(request.getScheme());
            builder.append("://");
            builder.append(request.getServerName());
            if ((request.getScheme().equals("https") && request.getServerPort() != 443)
                    || (request.getScheme().equals("http") && request.getServerPort() != 80)) {
                builder.append(':');
                builder.append(request.getServerPort());
            }
            builder.append(request.getRequestURI());

            // construct msg
            final StringBuilder buffer = new StringBuilder();
            String text = resBundle.getString("You've received a new form based mail from {0}.");
            text = text.replace("{0}", builder.toString());
            buffer.append(text);
            buffer.append("\n\n");
            buffer.append(resBundle.getString("Values"));
            buffer.append(":\n\n");
            // we sort the names first - we use the order of the form field and
            // append all others at the end (for compatibility)

            // let's get all parameters first and sort them alphabetically!
            final List<String> contentNamesList = new ArrayList<String>();
            final Iterator<String> names = FormsHelper.getContentRequestParameterNames(request);
            while (names.hasNext()) {
                final String name = names.next();
                contentNamesList.add(name);
            }
            Collections.sort(contentNamesList);

            final List<String> namesList = new ArrayList<String>();
            final Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource());
            while (fields.hasNext()) {
                final Resource field = fields.next();
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field);
                for (final FieldDescription desc : descs) {
                    // remove from content names list
                    contentNamesList.remove(desc.getName());
                    if (!desc.isPrivate()) {
                        namesList.add(desc.getName());
                    }
                }
            }
            namesList.addAll(contentNamesList);

            // now add form fields to message
            // and uploads as attachments
            final List<RequestParameter> attachments = new ArrayList<RequestParameter>();
            for (final String name : namesList) {
                final RequestParameter rp = request.getRequestParameter(name);
                if (rp == null) {
                    //see Bug https://bugs.day.com/bugzilla/show_bug.cgi?id=35744
                    logger.debug("skipping form element {} from mail content because it's not in the request",
                            name);
                } else if (rp.isFormField()) {
                    buffer.append(name);
                    buffer.append(" : \n");
                    final String[] pValues = request.getParameterValues(name);
                    for (final String v : pValues) {
                        buffer.append(v);
                        buffer.append("\n");
                    }
                    buffer.append("\n");
                } else if (rp.getSize() > 0) {
                    attachments.add(rp);

                } else {
                    //ignore
                }
            }
            // if we have attachments we send a multi part, otherwise a simple email
            final Email email;
            if (attachments.size() > 0) {
                buffer.append("\n");
                buffer.append(resBundle.getString("Attachments"));
                buffer.append(":\n");
                final MultiPartEmail mpEmail = new MultiPartEmail();
                email = mpEmail;
                for (final RequestParameter rp : attachments) {
                    final ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(),
                            rp.getContentType());
                    mpEmail.attach(ea, rp.getFileName(), rp.getFileName());

                    buffer.append("- ");
                    buffer.append(rp.getFileName());
                    buffer.append("\n");
                }
            } else {
                email = new SimpleEmail();
            }

            email.setMsg(buffer.toString());
            // mailto
            for (final String rec : mailTo) {
                email.addTo(rec);
            }
            // cc
            final String[] ccRecs = values.get(CC_PROPERTY, String[].class);
            if (ccRecs != null) {
                for (final String rec : ccRecs) {
                    email.addCc(rec);
                }
            }
            // bcc
            final String[] bccRecs = values.get(BCC_PROPERTY, String[].class);
            if (bccRecs != null) {
                for (final String rec : bccRecs) {
                    email.addBcc(rec);
                }
            }

            // subject and from address
            final String subject = values.get(SUBJECT_PROPERTY, resBundle.getString("Form Mail"));
            email.setSubject(subject);
            final String fromAddress = values.get(FROM_PROPERTY, "");
            if (fromAddress.length() > 0) {
                email.setFrom(fromAddress);
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Sending form activated mail: fromAddress={}, to={}, subject={}, text={}.",
                        new Object[] { fromAddress, mailTo, subject, buffer });
            }
            localService.sendEmail(email);

        } catch (EmailException e) {
            logger.error("Error sending email: " + e.getMessage(), e);
            status = 500;
        }
    }
    // check for redirect
    String redirectTo = request.getParameter(":redirect");
    if (redirectTo != null) {
        int pos = redirectTo.indexOf('?');
        redirectTo = redirectTo + (pos == -1 ? '?' : '&') + "status=" + status;
        response.sendRedirect(redirectTo);
        return;
    }
    if (FormsHelper.isRedirectToReferrer(request)) {
        FormsHelper.redirectToReferrer(request, response,
                Collections.singletonMap("stats", new String[] { String.valueOf(status) }));
        return;
    }
    response.setStatus(status);
}

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);/*  w w  w  . j  a v  a 2s .co  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;//  www .  ja v  a  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:com.ms.commons.message.impl.sender.AbstractEmailSender.java

/**
 * Email/*from  w w  w  .  ja va  2 s . co m*/
 * 
 * @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: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  a  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: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.");
        }/*from   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;
}

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

protected void addCc(Email email, String cc) {
    String[] ccs = splitAndTrim(cc);
    if (ccs != null) {
        for (String c : ccs) {
            try {
                email.addCc(c);
            } catch (EmailException e) {
                throw new ProcessEngineException("Could not add " + c + " as cc recipient", e);
            }//  w  ww  .j  a va  2 s.com
        }
    }
}

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

private void setMailMessageHeaders(Email email, MailMessageHeaders headers) throws EmailException {
    email.setFrom(headers.getFrom());// w ww . j av  a 2 s  .  c om

    try {
        email.setSubject(MimeUtility.encodeText(headers.getSubject(), headers.getCharset(), null));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    for (String to : headers.getTo()) {
        email.addTo(to);
    }

    for (String cc : headers.getCc()) {
        email.addCc(cc);
    }

    for (String bcc : headers.getBcc()) {
        email.addBcc(bcc);
    }
}

From source file:org.cobbzilla.mail.sender.SmtpMailSender.java

@Override
public void send(SimpleEmailMessage message) throws EmailException {

    Email email = constructEmail(message);
    email.setHostName(config.getHost());
    email.setSmtpPort(config.getPort());
    if (config.getHasMailUser()) {
        email.setAuthenticator(new DefaultAuthenticator(config.getUser(), config.getPassword()));
    }/*from   ww w  . j ava 2s .  c om*/
    email.setTLS(config.isTlsEnabled());
    email.setSubject(message.getSubject());
    if (message.getToName() != null) {
        email.addTo(message.getToEmail(), message.getToName());
    } else {
        email.addTo(message.getToEmail());
    }
    if (message.getBcc() != null) {
        email.addBcc(message.getBcc());
    }
    if (message.getCc() != null) {
        email.addCc(message.getCc());
    }
    if (message.getFromName() != null) {
        email.setFrom(message.getFromEmail(), message.getFromName());
    } else {
        email.setFrom(message.getFromEmail());
    }

    sendEmail_internal(email);
}

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

protected void addCc(Email email, String cc) {
    String[] ccs = splitAndTrim(cc);
    if (ccs != null) {
        for (String c : ccs) {
            try {
                email.addCc(c);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + c + " as cc recipient", e);
            }//from ww w  . ja  v  a 2  s .co m
        }
    }
}