Example usage for org.apache.commons.mail HtmlEmail setHeaders

List of usage examples for org.apache.commons.mail HtmlEmail setHeaders

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail setHeaders.

Prototype

public void setHeaders(final Map<String, String> map) 

Source Link

Document

Used to specify the mail headers.

Usage

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * smtp??//from w w  w  . java  2  s  .c  o m
 * 
 * @param subject subject
 * @param htmlBody htmlBody
 * @param properties properties
 * @param from from
 * @param toList toList
 * @param ccList ccList
 * @param bccList bccList
 * @param embedUrls 
 * @throws EmailException EmailException
 */
@SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseStringBufferForStringAppends" })
public static void sendMail(String subject, String htmlBody, Map<String, String> properties, String from,
        List<String> toList, List<String> ccList, List<String> bccList, Map<String, URL> embedUrls)
        throws EmailException {
    HtmlEmail htmlEmail = getEmail();
    // from?
    if (!Strings.isNullOrEmpty(from)) {
        Address fromMailbox = parseMailbox(from);
        if (fromMailbox != null && StringUtils.isNotBlank(from)) {
            htmlEmail.setFrom(fromMailbox.getAddress(), fromMailbox.getName());
        }
    }
    // to?
    if (toList != null && !toList.isEmpty()) {
        for (String to : toList) {
            if (StringUtils.isNotBlank(to)) {
                Address toMailbox = parseMailbox(to);
                htmlEmail.addTo(toMailbox.getAddress(), toMailbox.getName());
            }
        }
    }
    // cc?
    if (ccList != null && !ccList.isEmpty()) {
        for (String cc : ccList) {
            if (StringUtils.isNotBlank(cc)) {
                Address ccMailbox = parseMailbox(cc);
                htmlEmail.addCc(ccMailbox.getAddress(), ccMailbox.getName());
            }
        }
    }
    // bcc?
    if (bccList != null && !bccList.isEmpty()) {
        for (String bcc : bccList) {
            if (StringUtils.isNotBlank(bcc)) {
                Address bccMailbox = parseMailbox(bcc);
                htmlEmail.addBcc(bccMailbox.getAddress(), bccMailbox.getName());
            }
        }
    }
    // 
    htmlEmail.setSubject(subject);
    htmlEmail.setHtmlMsg(htmlBody);
    htmlEmail.setSentDate(new Date());
    // 
    if (properties != null) {
        htmlEmail.setHeaders(properties);
    }
    // 
    if (embedUrls != null && !embedUrls.isEmpty()) {
        for (Map.Entry<String, URL> entry : embedUrls.entrySet()) {
            String cid = entry.getKey();
            URL url = entry.getValue();
            String fileName = StringUtils.substringAfterLast(url.getPath(), "/");
            if (StringUtils.isBlank(fileName)) {
                fileName = cid;
            } else {
                fileName += IdUtils.genStringId();
            }
            htmlEmail.embed(new URLDataSource(url), fileName, cid);
        }
    }
    htmlEmail.send();
}

From source file:de.jaide.courier.email.MessageHandlerEMail.java

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*/*from   w  w w. j  a  v  a2 s . com*/
     * Check if the obligatory parameters are there.
     */
    for (String key : obligatoryMappingParameters)
        if (!parameters.containsKey(key))
            throw new CourierException(new MissingParameterException(
                    "The parameter '" + key + "' was expected but couldn't be found."));

    /*
     * Now retrieve the obligatory parameters.
     */
    String configurationName = (String) parameters.get(MAPPING_PARAM_CONFIGURATION_NAME);
    String templatePath = (String) parameters.get(MAPPING_PARAM_TEMPLATE_PATH);
    if ((templatePath != null) && (!templatePath.endsWith("/")))
        templatePath += "/";
    else if (templatePath == null)
        templatePath = "/";

    Class<?> templatePathClass = (Class<?>) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_CLASS);
    File templatePathFile = (File) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_FILE);

    String templateName = (String) parameters.get(MAPPING_PARAM_TEMPLATE_NAME);
    TemplateTypeEnum templateTypeEnum = (TemplateTypeEnum) parameters.get(MAPPING_PARAM_TEMPLATE_TYPE);
    String recipientFirstname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_FIRSTNAME);
    String recipientLastname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_LASTNAME);
    String recipientEMail = (String) parameters.get(MAPPING_PARAM_RECIPIENT_EMAIL);
    String ccRecipientFirstname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_FIRSTNAME);
    String ccRecipientLastname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_LASTNAME);
    String ccRecipientEMail = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_EMAIL);

    /*
     * The next three parameters are optional, as they might also be specified in the SMTP configuration file. If they are specified they
     * tell us to overwrite what was specified in the SMTP configuration file and use those values (firstname, lastname, e-mail) for the
     * sender instead.
     */
    String senderFirstname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_FIRSTNAME))
        senderFirstname = (String) parameters.get(MAPPING_PARAM_SENDER_FIRSTNAME);

    String senderLastname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_LASTNAME))
        senderLastname = (String) parameters.get(MAPPING_PARAM_SENDER_LASTNAME);

    String senderEMail = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_EMAIL))
        senderEMail = (String) parameters.get(MAPPING_PARAM_SENDER_EMAIL);

    /*
     * Will be used for parsing the templates.
     */
    StringWriter writer = new StringWriter();

    try {
        /*
         * Construct the template that we're about to process. First set the path to load the template(s) from. In case a Directory was given
         * as the base for template loading purposes use that instead.
         */
        if (templatePathFile == null) {
            if (templatePathClass == null)
                templatingConfiguration.setClassForTemplateLoading(getClass(), templatePath);
            else
                templatingConfiguration.setClassForTemplateLoading(templatePathClass, templatePath);
        } else
            templatingConfiguration.setDirectoryForTemplateLoading(templatePathFile);

        /*
         * Get the headers and Freemarker-parse them. If there are no headers then ignore the errors. The file has to be one header per line,
         * header name and value separated by a colon (":").
         */
        Template template;

        Map<String, String> headers = new HashMap<String, String>();
        String headersFilename = retrieveTemplateFilename(templateName,
                MessageHandlerEMail.TEMPLATENAME_SUFFIX_HEADERS, true);
        if (headersFilename != null) {
            try {
                template = loadTemplate(headersFilename);
                template.process(parameters, writer);
                BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
                headers = new HashMap<String, String>();
                String str = "";
                while ((str = reader.readLine()) != null) {
                    String[] split = str.split(":");
                    if (split.length > 1)
                        headers.put(split[0].trim(), split[1].trim());
                }
            } catch (IOException ioe) {
                // The header file is optional, hence we don't care if it couldn't be found
            }
        }

        /*
         * Get the subject line and Freemarker-parse it.
         */
        String subject = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_SUBJECT,
                templateName, false);

        /*
         * Get the body content and Freemarker-parse it.
         */
        String contentText = null;
        String contentHtml = null;

        /*
         * Load all requested versions of the template.
         */
        if (templateTypeEnum == TemplateTypeEnum.TEXT) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
        } else if (templateTypeEnum == TemplateTypeEnum.HTML) {
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.BOTH) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.ANY) {
            try {
                contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                        templateName, false);
            } catch (IOException ioe) {
            } finally {
                try {
                    contentHtml = loadAndProcessTemplate(parameters,
                            MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true);
                } catch (IOException ioe) {
                    throw new RuntimeException(
                            "Neither the HTML nor the TEXT-only version of the e-mail template '" + templateName
                                    + "' could be found. Are you sure they reside in '" + templatePath
                                    + "' as '" + templateName + "_body.ftl.html' or '" + templateName
                                    + "_body.ftl.txt'?",
                            ioe);
                }
            }
        }

        /*
         * Set the parameters that are identical for that sender, for all recipients.
         * Note: attachments may not be removed once they have been attached, hence the performance-improving caching had to be removed.
         */
        SmtpConfiguration smtpConfiguration = (SmtpConfiguration) smtpConfigurations.get(configurationName);
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset("UTF-8");
        htmlEmail.setHostName(smtpConfiguration.getSmtpHostname());
        htmlEmail.setSmtpPort(smtpConfiguration.getSmtpPort());
        if (smtpConfiguration.isTls()) {
            htmlEmail.setAuthenticator(
                    new DefaultAuthenticator(smtpConfiguration.getUsername(), smtpConfiguration.getPassword()));
            htmlEmail.setStartTLSEnabled(smtpConfiguration.isTls());
        }
        htmlEmail.setSSLOnConnect(smtpConfiguration.isSsl());

        /*
         * Changing the sender, to differ from what was specified in the particular SMTP configuration, is optional. As explained above this
         * will only happen if they were specified by the caller.
         */
        if ((senderFirstname != null) || (senderLastname != null) || (senderEMail != null))
            htmlEmail.setFrom(senderEMail, senderFirstname + " " + senderLastname);
        else
            htmlEmail.setFrom(smtpConfiguration.getFromEMail(), smtpConfiguration.getFromSenderName());

        /*
         * Set the parameters that differ for each recipient.
         */
        htmlEmail.addTo(recipientEMail, recipientFirstname + " " + recipientLastname);
        if ((ccRecipientFirstname != null) && (ccRecipientLastname != null) && (ccRecipientEMail != null))
            htmlEmail.addCc(ccRecipientEMail, ccRecipientFirstname + " " + ccRecipientLastname);
        htmlEmail.setHeaders(headers);
        htmlEmail.setSubject(subject);

        /*
         * Set the HTML and Text version of the e-mail body.
         */
        if (contentHtml != null)
            htmlEmail.setHtmlMsg(contentHtml);
        if (contentText != null)
            htmlEmail.setTextMsg(contentText);

        /*
         * Add attachments, if available.
         */
        if (parameters.containsKey(MAPPING_PARAM_ATTACHMENTS)) {
            @SuppressWarnings("unchecked")
            List<EmailAttachment> attachments = (List<EmailAttachment>) parameters
                    .get(MAPPING_PARAM_ATTACHMENTS);
            for (EmailAttachment attachment : attachments) {
                htmlEmail.attach(attachment);
            }
        }

        /*
         * Finished - now send the e-mail.
         */
        htmlEmail.send();
    } catch (IOException ioe) {
        throw new CourierException(ioe);
    } catch (TemplateException te) {
        throw new CourierException(te);
    } catch (EmailException ee) {
        throw new CourierException(ee);
    } finally {
        if (writer != null) {
            writer.flush();

            try {
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}