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

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

Introduction

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

Prototype

public HtmlEmail setTextMsg(final String aText) throws EmailException 

Source Link

Document

Set the text content.

Usage

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

public void sendingHtml() {
    try {//from   w  w w .j  a v a  2 s.  co  m
        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        email.setSubject("TestMail");
        email.addTo("belchiorpalma@gmail.com", "Belchior Palma");
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject("Test email with inline image");
        email.setSubject(MimeUtility.encodeText("Test email with inline image", "UTF-8", "B"));

        // embed the image and get the content id
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo");

        // set the html message
        email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>");

        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Email.CommonsEmail.java

/**
 * funo para enviar email/*  w  w  w.  ja  va  2s  .  co 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:controllers.ProjectApp.java

private static void sendTransferRequestMail(ProjectTransfer pt) {
    HtmlEmail email = new HtmlEmail();
    try {/*from w w  w . j  av a  2 s . c  o  m*/
        String acceptUrl = pt.getAcceptUrl();
        String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n"
                + Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner,
                        pt.destination)
                + "\n" + Messages.get("transfer.message.link") + "\n\n" + acceptUrl + "\n\n"
                + Messages.get("transfer.message.deadline") + "\n\n" + Messages.get("transfer.message.thank");

        email.setFrom(Config.getEmailFromSmtp(), pt.sender.name);
        email.addTo(Config.getEmailFromSmtp(), "Yobi");

        User to = User.findByLoginId(pt.destination);
        if (!to.isAnonymous()) {
            email.addBcc(to.email, to.name);
        }

        Organization org = Organization.findByName(pt.destination);
        if (org != null) {
            List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org);
            for (OrganizationUser admin : admins) {
                email.addBcc(admin.user.email, admin.user.name);
            }
        }

        email.setSubject(
                String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId));
        email.setHtmlMsg(Markdown.render(message));
        email.setTextMsg(message);
        email.setCharset("utf-8");
        email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">");
        email.setSentDate(pt.requested);
        Mailer.send(email);
        String escapedTitle = email.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * /*from  www .ja v a2 s. c  o  m*/
 * Envoi l'email.
 * 
 * @throws EmailException
 *             Erreur lors de l'envoi de l'email.
 */
public void send() throws EmailException {

    if (hostProperty == null) {
        log.error("Session email non initialise : envoi des emails impossible.");
        return;
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(hostProperty);

    // To
    if (to != null) {
        for (String adresse : to) {
            email.addTo(adresse);
        }
    }

    // Cc
    if (cc != null) {
        for (String adresse : cc) {
            email.addCc(adresse);
        }
    }

    // Cci
    if (cci != null) {
        for (String adresse : cci) {
            email.addBcc(adresse);
        }
    }

    // Subject
    email.setSubject(subjectPrefix != null ? subjectPrefix + subject : subject);

    // From
    email.setFrom(StringUtils.isNotEmpty(from) ? from : defaultFrom);

    // Message & Html
    if (message != null) {
        email.setTextMsg(message);
    }
    if (html != null) {
        email.setHtmlMsg(html);
    }

    if (StringUtils.isNotEmpty(this.charset)) {
        email.setCharset(this.charset);
    }

    email.buildMimeMessage();

    // Attachments
    for (AttachmentBean attachement : attachments) {
        email.attach(attachement.getDataSource(), attachement.getName(), attachement.getDescription());
    }

    email.sendMimeMessage();

}

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {/*from   ww w .  j av  a  2s.  c om*/

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        URL url = linkBoleto;//new URL(linkBoleto);
        String cid = email.embed(url, new BusinessDelegate().getMensagem(new BigDecimal(61)).getAssunto());

        // localizando a mensagem
        //Mensagem msg = new Mensagem();
        //msg = new BusinessDelegate().getMensagem(mensagemId);

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        body += (this.bodyProfissional);
        body += ("Fa&ccedil;a Download do Boleto para pagamento: - <a href=" + url
                + " target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        body += "<img src=\"cid:" + cid + "\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(null);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.ufg.reqweb.components.MailBean.java

public void sendMailToDiscente(final Requerimento requerimento) {
    Thread sender = new Thread() {
        @Override//from   www. j av a 2 s .  c o  m
        public void run() {
            try {
                Configuration templateConf = new Configuration();
                templateConf.setObjectWrapper(new DefaultObjectWrapper());
                templateConf.setDefaultEncoding("UTF-8");
                templateConf.setDirectoryForTemplateLoading(new File(context.getRealPath("/reports/mail")));
                Map objectRoot = new HashMap();
                objectRoot.put("TITULO", LocaleBean.getDefaultMessageBundle().getString("appTitle"));
                objectRoot.put("DISCENTE", LocaleBean.getDefaultMessageBundle().getString("discente"));
                objectRoot.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento"));
                objectRoot.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status"));
                objectRoot.put("ATENDENTE", LocaleBean.getDefaultMessageBundle().getString("atendente"));
                objectRoot.put("OBSERVACAO", LocaleBean.getDefaultMessageBundle().getString("observacao"));
                objectRoot.put("matricula", requerimento.getDiscente().getMatricula());
                objectRoot.put("discente", requerimento.getDiscente().getNome());
                objectRoot.put("tipoRequerimento", LocaleBean.getDefaultMessageBundle()
                        .getString(requerimento.getTipoRequerimento().getTipo()));
                objectRoot.put("status",
                        LocaleBean.getDefaultMessageBundle().getString(requerimento.getStatus().getStatus()));
                objectRoot.put("atendente", requerimento.getAtendimento().getAtendente().getNome());
                objectRoot.put("observacao", requerimento.getAtendimento().getObservacao());
                URL logo = new File(context.getRealPath("/resources/img/logo-mono-mini.png")).toURI().toURL();
                Template template = templateConf.getTemplate("notificacao_discente.ftl");
                Writer writer = new StringWriter();
                HtmlEmail email = new HtmlEmail();
                String logoId = email.embed(logo, "logo");
                objectRoot.put("logo", logoId);
                template.process(objectRoot, writer);
                email.setHostName(configDao.getValue("mail.mailHost"));
                email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort")));
                String mailSender = configDao.getValue("mail.mailSender");
                String user = configDao.getValue("mail.mailUser");
                String password = configDao.getValue("mail.mailPassword");
                boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL"));
                email.setAuthenticator(new DefaultAuthenticator(user, password));
                email.setSSLOnConnect(useSSL);
                email.setFrom(mailSender);
                email.addTo(requerimento.getDiscente().getEmail());
                email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail"));
                email.setHtmlMsg(writer.toString());
                String alternativeMessage = String.format("%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
                        LocaleBean.getDefaultMessageBundle().getString("messageMail"),
                        objectRoot.get("REQUERIMENTO"), objectRoot.get("tipoRequerimento"),
                        objectRoot.get("STATUS"), objectRoot.get("status"), objectRoot.get("ATENDENTE"),
                        objectRoot.get("atendente"), objectRoot.get("OBSERVACAO"),
                        objectRoot.get("observacao"));
                email.setTextMsg(alternativeMessage);
                email.send();
                System.out.println(String.format("message to discente:<%s: %s>",
                        requerimento.getDiscente().getNome(), requerimento.getDiscente().getEmail()));
            } catch (EmailException | IOException | TemplateException e) {
                System.out.println("erro ao enviar email");
                System.out.println(e);
            }
        }
    };
    sender.start();
}

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

/**
*
* @param destinatario//  w  w  w  .j  a  v  a2 s.  c o m
* @param nome
* @param assunto
* @throws IOException
*/

public void sendingHtml(String destinatario, String nome, String assunto, int tipoId) throws IOException {
    try {

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        //email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        // URL url = linkBoleto;//new URL(linkBoleto);
        //String cid = email.embed(url, "Congresso TRT 15");

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        if (tipoId == 1) {
            body += (this.bodyProfissional);
        } else if (tipoId == 2) {
            body += (this.bodyServidor);
        } else if (tipoId == 3) {
            body += (this.bodyMagistrado);
        } else if (tipoId == 4) {
            body += (this.bodyEstudante);
        } else {
            body += "Congresso TRT";
        }

        // body+=("Faa Download do Boleto para pagamento: - <a href="+url+" target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        //body+="<img src=\"cid:"+cid+"\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(CONTENT_TYPE);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        // utils.Logger.getLogger("Erro ao enviar Email. "+tipoId+" - "+ex.toString(),tipoId);
        // utils.Logger.getLoggerPessoaFisica("Erro ao enviar email - sending html:"+ex.getMessage());
    }

}

From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {//  w  w  w. j ava 2  s .  co m

        // Create the email message
        //MultiPartEmail email = new MultiPartEmail();   
        StringBuilder strHtmlContentSummary = new StringBuilder();
        System.out.println("Analysis -  Sonar Email Notification");
        from = settings.getString("sonar.jd.smptp.username");
        System.out.println("from=>" + from);
        to_email = settings.getString("sonar.jd.smptp.to");
        System.out.println("to_email=>" + to_email);

        to_email_name = settings.getString("sonar.jd.smptp.to_name");
        System.out.println("to_email_name=>" + to_email_name);

        username = settings.getString("sonar.jd.smptp.username");
        System.out.println("username=>" + username);
        password = settings.getString("sonar.jd.smptp.password");
        System.out.println("password=>" + password);
        hostname = settings.getString("sonar.jd.smptp.host");
        System.out.println("hostname=>" + hostname);
        portno = settings.getString("sonar.jd.smptp.sslport");
        System.out.println("portno=>" + portno);
        setSSLOnConnectFlag = settings.getBoolean("sonar.jd.smptp.set_ssl_on_connect");
        System.out.println("setSSLOnConnectFlag=>" + String.valueOf(setSSLOnConnectFlag));
        subject = settings.getString("sonar.jd.smptp.subject");
        System.out.println("subject=>" + subject);
        message = settings.getString("sonar.jd.smptp.message");
        System.out.println("message=>" + message);

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostname);
        email.setSslSmtpPort(portno);
        if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) {
            email.setAuthentication(username, password);
        }
        //email.setSSLOnConnect(setSSLOnConnectFlag);
        email.setSSL(setSSLOnConnectFlag);
        String[] addrs = StringUtils.split(to_email, "\t\r\n;, ");
        for (String addr : addrs) {
            email.addTo(addr);
        }
        //email.addTo(to_email,to_email_name);
        email.setFrom(from);
        email.setSubject(subject);
        //email.setMsg(message);

        // embed the image and get the content id   
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo - 1");

        System.out.println("Print Entries from Analysis Data Map.");
        int i = 1;
        strHtmlContentSummary.append("<html><body>The apache logo - <img src=\"cid:" + cid
                + "\"><br><br><br><b><center>Metric Information:-</center></b><br><table border='2'>");
        for (Map.Entry<String, String> entry : reportDataMap.entrySet()) {
            strHtmlContentSummary
                    .append("<tr><td>" + entry.getKey() + ":</td><td>" + entry.getValue() + "</td></tr>");
            i++;
        }
        strHtmlContentSummary.append("</table></body></html>");
        System.out.println(strHtmlContentSummary.toString());
        // set the html message
        email.setHtmlMsg(strHtmlContentSummary.toString());
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(reportname);

        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sonar Analysis Report" + reportname);
        attachment.setName(reportname);
        email.attach(attachment);
        // send the email
        System.out.println("Sending the Email");
        email.send();
    } catch (EmailException e) {
        throw new SonarException("Unable to send email", e);
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

}

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

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*/*from w w w .  ja v a 2s . co 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:br.com.itfox.utils.SendHtmlFormatedEmail.java

public void sendingHtml(String orderDetails, String orderNumber, String toName, String toEmail) {
    try {/*from  w  ww . ja  va2  s.c om*/
        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("belchiorpalma@gmail.com", "xp2002b5"));
        email.setSSLOnConnect(true);
        email.setTLS(true);
        email.setFrom("contato@itfox.com.br");
        //email.setSubject("TestMail");
        email.addTo(toEmail, toName);
        //email.setFrom("belchiorpalma@me.com", "Me");
        //email.setSubject("Test email with inline image");
        email.setSubject(MimeUtility.encodeText("Thank you for your order", "UTF-8", "B"));

        // embed the image and get the content id
        //URL url = new URL("http://boutiquecellars.com/img/white-wines.jpg");
        //String cid = email.embed(url, "BoutiqueCellars.com");

        // set the html message
        email.setHtmlMsg("Thank you for your order\n<br/><br/>" + "\n" + "We received your order #"
                + orderNumber + " and we are working on it now.\n<br/>"
                + "We will e-mail you an update as soon as your order is processed.\n<br/>" + "\n<br/>"
                + "Boutique Cellars team\n"
                + "\n<br/><br/><img src='http://boutiquecellars.com/img/logoemail.jpg'/> \n" +
                //orderDetails +
                "<br/><br/>BOUTIQUE CELLARS SUPPORTS THE RESPONSIBLE SERVICE OF ALCOHOL. NSW: UNDER THE LIQUOR\n<br/>"
                + "ACT 2007 IT IS AGAINST THE LAW TO SELL OR SUPPLY ALCOHOL TO, OR TO OBTAIN ALCOHOL ON\n<br/>"
                + "BEHALF OF, A PERSON UNDER THE AGE OF 18 YEARS. NSW PACKAGED LIQUOR LICENCE NUMBER\n<br/>"
                + "LIQP770016947. YOUR CONTRACT OF SALE IS WITH THE RELEVANT LICENSEE AT THE RELEVANT\n<br/>"
                + "PREMISES FROM WHICH YOU ORDER IS ACCEPTED AND FULFILLED. LIQUOR IS SOLD FROM OUR\n<br/>"
                + "PLATFORM ON BEHALF OF THE RELEVANT LICENSEE. ACCORDINGLY, YOUR OFFER TO PURCHASE IS\n<br/>"
                + "SUBJECT TO ACCEPTANCE OF YOUR OFFER BY THE HOLDER OF THE LIQUOR LICENCE, CERTIFICATION\n<br/>"
                + "AND EVIDENCE OF YOU BEING OVER 18 YEARS OF AGE, THE AVAILABILITY OF STOCK AND THE\n<br/>"
                + "LIQUOR WHICH IS THE SUBJECT MATTER OF YOUR OFFER BEING ASCERTAINED AND APPROPRIATED\n<br/>"
                + "AT THE ABOVE MENTIONED LICENSED PREMISES.<br/><br/>"
                + " Boutique Cellar Imports Pty Ltd | ABN 69 607 265 618");

        // set the alternative message
        email.setTextMsg(
                "Thank you for your order, We received your order #18765 and we are working on it now.\n"
                        + "We will e-mail you an update as soon as your order is processed.\n" + "\n"
                        + "Boutique Cellars team");

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
    /*} catch (MalformedURLException ex) {
     Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }*/

}