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

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

Introduction

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

Prototype

public MultiPartEmail attach(final File file) throws EmailException 

Source Link

Document

Attach a file.

Usage

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

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*/*from   w ww. j  a  v a2 s  . c om*/
     * 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();
            }
        }
    }
}

From source file:org.fao.geonet.util.MailUtil.java

/**
 * Send an html mail with atachments//from   ww w . j a  v a2 s. c o m
 *
 * @param toAddress
 * @param from
 * @param subject
 * @param htmlMessage
 * @param attachment
 * @throws EmailException
 */
public static Boolean sendHtmlMailWithAttachment(List<String> toAddress, String from, String subject,
        String htmlMessage, List<EmailAttachment> attachment, SettingManager settings) {
    // Create data information to compose the mail
    HtmlEmail email = new HtmlEmail();
    String username = settings.getValue(Settings.SYSTEM_FEEDBACK_MAILSERVER_USERNAME);
    String password = settings.getValue(Settings.SYSTEM_FEEDBACK_MAILSERVER_PASSWORD);
    Boolean ssl = settings.getValueAsBool(Settings.SYSTEM_FEEDBACK_MAILSERVER_SSL, false);
    Boolean tls = settings.getValueAsBool(Settings.SYSTEM_FEEDBACK_MAILSERVER_TLS, false);

    String hostName = settings.getValue(Settings.SYSTEM_FEEDBACK_MAILSERVER_HOST);
    Integer smtpPort = Integer.valueOf(settings.getValue(Settings.SYSTEM_FEEDBACK_MAILSERVER_PORT));
    Boolean ignoreSslCertificateErrors = settings
            .getValueAsBool(Settings.SYSTEM_FEEDBACK_MAILSERVER_IGNORE_SSL_CERTIFICATE_ERRORS, false);

    configureBasics(hostName, smtpPort, from, username, password, email, ssl, tls, ignoreSslCertificateErrors);

    for (EmailAttachment attach : attachment) {
        try {
            email.attach(attach);
        } catch (EmailException e) {
            Log.error(LOG_MODULE_NAME, "Error attaching attachment " + attach.getName(), e);
        }
    }

    email.setSubject(subject);
    try {
        email.setHtmlMsg(htmlMessage);
    } catch (EmailException e1) {
        Log.error(LOG_MODULE_NAME, "Error setting email HTML message", e1);
        return false;
    }

    // send to all mails extracted from settings
    for (String add : toAddress) {
        try {
            email.addBcc(add);
        } catch (EmailException e) {
            Log.error(LOG_MODULE_NAME, "Error setting email BCC address " + add, e);
            return false;
        }
    }

    return send(email);
}

From source file:org.jkandasa.email.blaster.EmailUtils.java

public static void sendEmail(AppProperties appProperties, Address address) throws EmailException, IOException {
    HtmlEmail email = initializeEmail(appProperties);
    StringBuilder attachmentBuilder = new StringBuilder();

    String[] attachments = appProperties.getAttachments().split(",");
    for (String attachment : attachments) {
        File img = new File(attachment);
        if (appProperties.isEmbeddedAttachments()) {
            attachmentBuilder.append("<br><img src=cid:").append(email.embed(img)).append(">");
        } else {/*from   w ww. jav  a  2 s .c  om*/
            email.attach(img);
        }
    }

    email.setSubject(getSubject(appProperties, address));
    email.setHtmlMsg(getMessage(appProperties, address).replaceAll(ATTACHMENTS, attachmentBuilder.toString()));
    email.addTo(address.getEmails().split(EMAIL_SEPARATOR));
    String sendReturn = email.send();
    _logger.debug("Send Status:[{}]", sendReturn);
    _logger.debug("Email successfully sent to [{}]", address);
}

From source file:org.ms123.common.workflow.tasks.TaskMailExecutor.java

protected HtmlEmail createHtmlEmail(DelegateExecution execution, String text, String html,
        String attachmentPath) {/* w w  w . j  a  v a2  s .c o  m*/
    HtmlEmail email = new HtmlEmail();
    try {
        if (html != null) {
            email.setHtmlMsg(html);
        }
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        if (attachmentPath != null) {
            email.attach(
                    createAttachment(new File(getProcessDocBasedir(execution), attachmentPath).toString()));
        }
        return email;
    } catch (EmailException e) {
        throw new RuntimeException("TaskMailExecutor:Could not create HTML email", e);
    }
}

From source file:org.ms123.common.workflow.TaskSendExecutor.java

protected HtmlEmail createHtmlEmail(DelegateExecution execution, String text, String html,
        String attachmentPath) {//from  ww w . j  av  a  2s .co m
    HtmlEmail email = new HtmlEmail();
    try {
        if (html != null) {
            email.setHtmlMsg(html);
        }
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        if (attachmentPath != null) {
            email.attach(
                    createAttachment(new File(getProcessDocBasedir(execution), attachmentPath).toString()));
        }
        return email;
    } catch (EmailException e) {
        throw new RuntimeException("TaskSendExecutor:Could not create HTML email", e);
    }
}

From source file:util.Log.java

public static void relatarExceptionEmail(String className, String exception, String logPath) {
    /*//w w  w.  j a  v a  2  s.c om
     * Para compreender melhor acesse esse site:
     * http://www.botecodigital.info/java/enviando-e-mail-em-java-com-api-
     * commons-email-da-apache/
     */
    HtmlEmail email = new HtmlEmail();
    email.setSSLOnConnect(true);
    email.setHostName("smtp.gmail.com");
    email.setSslSmtpPort("465");
    email.setAuthenticator(new DefaultAuthenticator("jjsoftwares10@gmail.com", "jean1420"));
    try {
        email.setFrom("jjsoftwares10@gmail.com", "Software da clinica");
        email.setSubject("Exceo ocorrida no app da clinica");
        StringBuilder msg = new StringBuilder();
        msg.append("<h1 style=\"text-align: center;\">Excecao Ocorrida</h1>");
        msg.append("<p><strong>Na Classe: " + className + " </strong></p>");
        msg.append("<p><strong>Data e Horario do ocorrido: "
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:s"))
                + "</strong></p>");
        msg.append("<h2 style=\"text-align: center;\"><strong>Excecao</strong></h2>");
        msg.append("<p><span style=\"color: #ff0000;\">" + exception + "</span></p>");
        msg.append("<p><strong>Segue anexo com detalhes</strong></p>");
        /*Enviando o anexo com detalhes da exceo*/
        File arqLog = new File(logPath);
        if (arqLog.exists()) {
            EmailAttachment anexo = new EmailAttachment();
            anexo.setPath(logPath);
            anexo.setDisposition(EmailAttachment.ATTACHMENT);
            anexo.setName(arqLog.getName());
            email.attach(anexo);
        }
        /*enviando*/
        email.setHtmlMsg(msg.toString());
        email.addTo("jeandersonfju@gmail.com");
        email.addTo("jeff-assis@hotmail.com");
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();

    }
}