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

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

Introduction

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

Prototype

public Email setStartTLSEnabled(final boolean startTlsEnabled) 

Source Link

Document

Set or disable the STARTTLS encryption.

Usage

From source file:com.mycollab.module.mail.DefaultMailer.java

private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail,
        List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) {
    try {//from w  w w .  jav a  2  s  .  c  o m
        HtmlEmail email = new HtmlEmail();
        email.setHostName(emailConf.getHost());
        email.setSmtpPort(emailConf.getPort());
        email.setStartTLSEnabled(emailConf.getIsStartTls());
        email.setSSLOnConnect(emailConf.getIsSsl());
        email.setFrom(fromEmail, fromName);
        email.setCharset(EmailConstants.UTF_8);
        for (MailRecipientField aToEmail : toEmail) {
            if (isValidate(aToEmail.getEmail()) && isValidate(aToEmail.getName())) {
                email.addTo(aToEmail.getEmail(), aToEmail.getName());
            } else {
                LOG.error(String.format("Invalid to email input: %s---%s", aToEmail.getEmail(),
                        aToEmail.getName()));
            }
        }

        if (CollectionUtils.isNotEmpty(ccEmail)) {
            for (MailRecipientField aCcEmail : ccEmail) {
                if (isValidate(aCcEmail.getEmail()) && isValidate(aCcEmail.getName())) {
                    email.addCc(aCcEmail.getEmail(), aCcEmail.getName());
                } else {
                    LOG.error(String.format("Invalid cc email input: %s---%s", aCcEmail.getEmail(),
                            aCcEmail.getName()));
                }
            }
        }

        if (CollectionUtils.isNotEmpty(bccEmail)) {
            for (MailRecipientField aBccEmail : bccEmail) {
                if (isValidate(aBccEmail.getEmail()) && isValidate(aBccEmail.getName())) {
                    email.addBcc(aBccEmail.getEmail(), aBccEmail.getName());
                } else {
                    LOG.error(String.format("Invalid bcc email input: %s---%s", aBccEmail.getEmail(),
                            aBccEmail.getName()));
                }
            }
        }

        if (emailConf.getUser() != null) {
            email.setAuthentication(emailConf.getUser(), emailConf.getPassword());
        }

        email.setSubject(subject);

        if (StringUtils.isNotBlank(html)) {
            email.setHtmlMsg(html);
        }

        return email;
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}

From source file:org.meruvian.yama.webapi.config.EmailConfig.java

@Bean
@Scope("prototype")
public HtmlEmail email() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(props.getProperty("host"));
    email.setSmtpPort(props.getProperty("port", Integer.class, 0));
    email.setAuthentication(props.getProperty("username"), props.getProperty("password"));
    email.setFrom(props.getProperty("from_email"), props.getProperty("from_alias"));
    email.setSSLOnConnect(props.getProperty("ssl", Boolean.class, false));
    email.setStartTLSEnabled(props.getProperty("tls", Boolean.class, false));

    return email;
}

From source file:enviocorreo.EnviadorCorreo.java

/**
 * Enva un correo electrnico. Utiliza la biblioteca Apache Commons Email,
 * accesible va <a href="https://commons.apache.org/proper/commons-email/">https://commons.apache.org/proper/commons-email/</a>
 *
 * @param destinatario//from   w w  w  .  j  a  va  2s . c  o  m
 * @param asunto
 * @param mensaje
 * @return
 */
public boolean enviarCorreoE(String destinatario, String asunto, String mensaje) {
    boolean resultado = false;

    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setSmtpPort(puerto);
    email.setAuthenticator(new DefaultAuthenticator(usuario, password));

    if (isGmail) {
        email.setSSLOnConnect(true);
    } else {
        email.setStartTLSEnabled(true);
    }

    try {
        email.setFrom(usuario + "<dominio del correo>");
        email.setSubject(asunto);
        email.setHtmlMsg(mensaje);
        email.addTo(destinatario);
        email.send();
        resultado = true;
    } catch (EmailException eme) {
        mensaje = "Ocurri un error al hacer el envo de correo.";
        mensajeError = eme.toString();
    }

    return resultado;
}

From source file:Email.CommonsEmail.java

/**
 * funo para enviar email// w ww .  j  a  va 2 s. c o  m
 *
 * @param titulo
 * @param msgEmail
 * @param emailDestinatarios
 * @return
 */
public boolean enviarEmail(String titulo, String msgEmail, String emailDestinatarios) {
    boolean enviado = false;
    String para = emailDestinatarios.toLowerCase().trim();
    String subject = titulo.trim();
    String msg = msgEmail.trim();

    try {
        StringTokenizer stPara = new StringTokenizer(para, ";");

        while (stPara.hasMoreTokens()) {
            if (!stPara.toString().trim().equals("")) {
                HtmlEmail email = new HtmlEmail();
                /*o servidor SMTP para envio do e-mail*/
                email.setHostName(emailConfig.getHostname());
                email.setSmtpPort(emailConfig.getPorta());
                email.setSSLOnConnect(emailConfig.getSsl());
                email.setStartTLSEnabled(emailConfig.getTsl());

                /*remetente*/
                email.setFrom(emailConfig.getEmail(), emailConfig.getNome());
                email.setAuthentication(emailConfig.getUsuario(), emailConfig.getSenha());
                /* ---------------------------------------------------------- */
                //destinatrio
                //email.addTo(emailDestinatario, nomeDestinatario);
                email.addTo(stPara.nextToken().trim());
                // assunto do e-mail
                email.setSubject(subject);

                //conteudo do e-mail
                //configura a mensagem para o formato HTML
                email.setHtmlMsg(msg);
                // configure uma mensagem alternativa caso o servidor no suporte HTML
                email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

                // envia email
                email.send();
                enviado = true;
            }
        }
    } catch (EmailException ex) {
        enviado = false;
        Logger.getLogger(CommonsEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
    return enviado;
}

From source file:dk.dma.ais.abnormal.analyzer.reports.ReportMailer.java

/**
 * Send email with subject and message body.
 * @param subject the email subject.// w w w  .  j a v  a2  s  .c o m
 * @param body the email body.
 */
public void send(String subject, String body) {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_HOST, "localhost"));
        email.setSmtpPort(configuration.getInt(CONFKEY_REPORTS_MAILER_SMTP_PORT, 465));
        email.setAuthenticator(
                new DefaultAuthenticator(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_USER, "anonymous"),
                        configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_PASS, "guest")));
        email.setStartTLSEnabled(false);
        email.setSSLOnConnect(configuration.getBoolean(CONFKEY_REPORTS_MAILER_SMTP_SSL, true));
        email.setFrom(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_FROM, ""));
        email.setSubject(subject);
        email.setHtmlMsg(body);
        String[] receivers = configuration.getStringArray(CONFKEY_REPORTS_MAILER_SMTP_TO);
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        email.send();
        LOG.info("Report sent with email to " + email.getToAddresses().toString() + " (\"" + subject + "\")");
    } catch (EmailException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.dattack.jtoolbox.commons.email.HtmlEmailBuilder.java

/**
 * Builder method.//  w w  w . j  a  v a 2  s.  com
 *
 * @return the HtmlEmail
 * @throws EmailException
 *             if an error occurs while creating the email
 */
public HtmlEmail build() throws EmailException {

    if (hostname == null || hostname.isEmpty()) {
        throw new EmailException(String.format("Invalid SMTP server (hostname: '%s')", hostname));
    }

    if (from == null || from.isEmpty()) {
        throw new EmailException(String.format("Invalid email address (FROM: '%s'", from));
    }

    final HtmlEmail email = new HtmlEmail();
    email.setHostName(hostname);
    email.setFrom(from);
    email.setSubject(subject);

    if (message != null && !message.isEmpty()) {
        email.setMsg(message);
    }

    if (port > 0) {
        email.setSmtpPort(port);
    }

    if (username != null && !username.isEmpty()) {
        email.setAuthenticator(new DefaultAuthenticator(username, password));
    }

    if (sslOnConnect != null) {
        email.setSSLOnConnect(sslOnConnect);
    }

    if (startTlsEnabled != null) {
        email.setStartTLSEnabled(startTlsEnabled);
    }

    if (!toList.isEmpty()) {
        email.setTo(toList);
    }

    if (!ccList.isEmpty()) {
        email.setCc(ccList);
    }

    if (!bccList.isEmpty()) {
        email.setBcc(bccList);
    }
    return email;
}

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;//from  w ww.  ja v a  2 s.c  o  m
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

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

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*//from www.  j  av  a2  s. c o  m
     * 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:com.esofthead.mycollab.module.mail.DefaultMailer.java

private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail,
        List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) {
    try {/* ww w  .  java  2s. co  m*/
        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setFrom(fromEmail, fromName);
        email.setCharset(EmailConstants.UTF_8);
        for (int i = 0; i < toEmail.size(); i++) {
            if (isValidate(toEmail.get(i).getEmail()) && isValidate(toEmail.get(i).getName())) {
                email.addTo(toEmail.get(i).getEmail(), toEmail.get(i).getName());
            } else {
                LOG.error("Invalid to email input: " + toEmail.get(i).getEmail() + "---"
                        + toEmail.get(i).getName());
            }
        }

        if (CollectionUtils.isNotEmpty(ccEmail)) {
            for (int i = 0; i < ccEmail.size(); i++) {
                if (isValidate(ccEmail.get(i).getEmail()) && isValidate(ccEmail.get(i).getName())) {
                    email.addCc(ccEmail.get(i).getEmail(), ccEmail.get(i).getName());
                } else {
                    LOG.error("Invalid cc email input: " + ccEmail.get(i).getEmail() + "---"
                            + ccEmail.get(i).getName());
                }
            }
        }

        if (CollectionUtils.isNotEmpty(bccEmail)) {
            for (int i = 0; i < bccEmail.size(); i++) {
                if (isValidate(bccEmail.get(i).getEmail()) && isValidate(bccEmail.get(i).getName())) {
                    email.addBcc(bccEmail.get(i).getEmail(), bccEmail.get(i).getName());
                } else {
                    LOG.error("Invalid bcc email input: " + bccEmail.get(i).getEmail() + "---"
                            + bccEmail.get(i).getName());
                }
            }
        }

        if (username != null) {
            email.setAuthentication(username, password);
        }
        email.setStartTLSEnabled(isTLS);
        email.setSubject(subject);

        if (StringUtils.isNotBlank(html)) {
            email.setHtmlMsg(html);
        }

        return email;
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}