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

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

Introduction

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

Prototype

HtmlEmail

Source Link

Usage

From source file:br.com.hslife.imobiliaria.service.EmailService.java

/**
 * Envia email no formato HTML/*from  w  w  w  .  j  a  v  a2  s  .c o  m*/
 *
 * @param nomeRemetente
 * @param nomeDestinatario
 * @param emailRemetente
 * @param emailDestinatario
 * @param assunto
 * @param mensagem
 * @param anexo
 *
 * @throws EmailException
 * @throws MalformedURLException
 */
public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario,
        String emailDestinatario, String assunto, StringBuilder mensagem, String anexo)
        throws EmailException, MalformedURLException {

    HtmlEmail email = new HtmlEmail();

    // adiciona uma imagem ao corpo da mensagem e retorna seu id
    URL url = new URL(anexo); // URL do arquivo a ser anexado
    String cid = email.embed(url, "Anexos");

    // configura a mensagem para o formato HTML
    email.setHtmlMsg("<html>Anexos</html>");

    // configure uma mensagem alternativa caso o servidor no suporte HTML
    email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

    email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail
    email.addTo(emailDestinatario, nomeDestinatario); //destinatrio
    email.setFrom(emailRemetente, nomeRementente); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(mensagem.toString()); //conteudo do e-mail
    email.setAuthentication("realimoveis@hslife.com.br", "real123");
    //email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);

    // envia email
    email.send();
}

From source file:br.com.hslife.catu.service.EmailService.java

/**
 * Envia email no formato HTML/*  ww w.j a  v  a2  s  . co  m*/
 *
 * @param nomeRemetente
 * @param nomeDestinatario
 * @param emailRemetente
 * @param emailDestinatario
 * @param assunto
 * @param mensagem
 * @param anexo
 *
 * @throws EmailException
 * @throws MalformedURLException
 */
public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario,
        String emailDestinatario, String assunto, StringBuilder mensagem, String anexo)
        throws EmailException, MalformedURLException {

    HtmlEmail email = new HtmlEmail();

    // adiciona uma imagem ao corpo da mensagem e retorna seu id
    URL url = new URL(anexo); // URL do arquivo a ser anexado
    String cid = email.embed(url, "Anexos");

    // configura a mensagem para o formato HTML
    email.setHtmlMsg("<html>Anexos</html>");

    // configure uma mensagem alternativa caso o servidor no suporte HTML
    email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

    email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail
    email.addTo(emailDestinatario, nomeDestinatario); //destinatrio
    email.setFrom(emailRemetente, nomeRementente); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(mensagem.toString()); //conteudo do e-mail
    email.setAuthentication("realimoveis@hslife.com.br", "real123");
    email.setCharset("UTF8");
    //email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);

    // envia email
    email.send();
}

From source file:fr.gael.dhus.service.job.SearchesJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSearchesCronConfiguration().isActive())
        return;//from www .  ja v a 2s  .c  om
    long time_start = System.currentTimeMillis();
    logger.info("SCHEDULER : User searches mailings.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }
    Map<String, String> cids = new HashMap<String, String>();
    for (User user : userDao.readNotDeleted()) {
        List<Search> searches = userDao.getUserSearches(user);
        if (searches == null || (searches.size() == 0)) {
            logger.debug("No saved search for user \"" + user.getUsername() + "\".");
            continue;
        }

        if (user.getEmail() == null) {
            logger.error(
                    "User \"" + user.getUsername() + "\" email not configured to send search notifications.");
            continue;
        }

        HtmlEmail he = new HtmlEmail();
        cids.clear();

        int maxResult = searches.size() >= 10 ? 5 : 10;
        String message = "<html><style>" + "a { font-weight: bold; color: #205887; "
                + "text-decoration: none; }\n" + "a:hover { font-weight:bold; color: #FF790B"
                + "; text-decoration: none; }\na img { border-style: none; }\n"
                + "</style><body style=\"font-family: Trebuchet MS, Helvetica, "
                + "sans-serif; font-size: 14px;\">Dear " + getUserWelcome(user) + ",<p/>\n\n";
        message += "You requested periodic notification for the following " + "searches. Here are the top "
                + maxResult + " results for " + "each search:<p/>";
        message += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" "
                + "style=\"width: 100%;font-family: Trebuchet MS, Helvetica, "
                + "sans-serif; font-size: 14px;\"><tbody>";

        boolean atLeastOneResult = false;
        for (Search search : searches) {
            if (search.isNotify()) {
                message += "<tr><td colspan=\"3\" style=\"font-size: 13px; "
                        + "font-weight: bold; color: white; background-color: "
                        + "#205887; text-align: center;\"><b>";
                message += search.getValue();
                message += "</b></td></tr>\n";

                Map<String, String> advanceds = search.getAdvanced();
                if (advanceds != null && !advanceds.isEmpty()) {
                    message += "<tr><td style=\"font-size: 13px; padding:0px; "
                            + "margin:0px; font-weight:normal; background-color: "
                            + "#799BB7; text-align: center; border-left: 1px solid "
                            + "#205887; border-right: 1px solid #205887; "
                            + "border-bottom: 1px solid #205887;\">";
                    boolean first = true;
                    List<String> keys = new ArrayList<String>(advanceds.keySet());
                    Collections.sort(keys);
                    String lastKey = "";
                    for (String key : keys) {
                        if ((lastKey + "End").equals(key)) {
                            message += " to " + advanceds.get(key);
                        } else {
                            if (key.endsWith("End")) {
                                message += (first ? "" : ", ") + key.substring(0, key.length() - 3) + ": * to "
                                        + advanceds.get(key);
                            } else {
                                message += (first ? "" : ", ") + key + ": " + advanceds.get(key);
                            }
                        }
                        first = false;
                        lastKey = key;
                    }
                    message += "</td></tr>";
                }

                Iterator<Product> results;
                try {
                    results = searchService.search(search.getComplete());
                } catch (Exception e) {
                    message += "<tr><td colspan=\"3\" style=\""
                            + "text-align: center; border-left: 1px solid #205887; "
                            + "border-right: 1px solid #205887;\">" + "No result found</td></tr>";
                    logger.debug("There was an error when executing query : \"" + e.getMessage() + "\"");
                    continue;
                }

                if (!results.hasNext()) {
                    message += "<tr><td colspan=\"3\" style=\""
                            + "text-align: center; border-left: 1px solid #205887; "
                            + "border-right: 1px solid #205887;\">" + "No result found</td></tr>";
                    logger.debug("No result matches query : \"" + search.getComplete() + "\"");
                }

                boolean first = true;
                int searchIndex = 0;
                while (results.hasNext() && searchIndex < maxResult) {

                    if (!first) {
                        message += "<tr><td colspan=\"3\" style=\""
                                + "background-color: #205887; height:1px;\" /></tr>";
                    }
                    first = false;

                    Product product = results.next();
                    // WARNING : must implement to schedule fix of this issue...
                    if (product == null)
                        continue;

                    atLeastOneResult = true;
                    searchIndex++;

                    logger.debug("Result found: " + product.getIdentifier());

                    String purl = configurationManager.getServerConfiguration().getExternalUrl()
                            + "odata/v1/Products('" + product.getUuid() + "')";

                    // EMBEDED THUMBNAIL
                    String cid = null;
                    if (product.getThumbnailFlag()) {
                        File thumbnail = new File(product.getThumbnailPath());
                        String thumbname = thumbnail.getName();
                        if (cids.containsKey(thumbname)) {
                            cid = cids.get(thumbname);
                        } else {
                            try {
                                cid = he.embed(thumbnail);
                                cids.put(thumbname, cid);
                            } catch (Exception e) {
                                logger.warn("Cannot embed image \"" + purl + "/Products('Quicklook')/$value\" :"
                                        + e.getMessage());
                                cid = null;
                            }
                        }
                    }
                    boolean downloadRight = user.getRoles().contains(Role.DOWNLOAD);
                    String link = downloadRight
                            ? "(<a target=\"_blank\" href=\"" + purl + "/$value\">download</a>)"
                            : "";
                    message += "   <tr><td colspan=\"3\" style=\"" + "font-size: 14px; text-align: center; "
                            + "border-left: 1px solid #205887; border-right: 1px "
                            + "solid #205887;\"><a target=\"_blank\" href=\"" + purl + "/$value\">"
                            + product.getIdentifier() + "</a> " + link + "</td>\n</tr>\n";
                    if (cid != null) {
                        message += "   <tr><td rowspan=\"8\" style=\""
                                + "text-align: center; vertical-align: middle;"
                                + " border-left: 1px solid #205887;\">" + "<a target=\"_blank\" href=\"" + purl
                                + "/Products('Quicklook')/$value\"><img src=cid:" + cid
                                + " style=\"max-height: 64px; max-width:" + " 64px;\"></a></td>\n";
                    }

                    // Displays metadata
                    List<MetadataIndex> indexes = new ArrayList<>(productService.getIndexes(product.getId()));
                    Collections.sort(indexes, new Comparator<MetadataIndex>() {
                        @Override
                        public int compare(MetadataIndex o1, MetadataIndex o2) {
                            if ((o1.getCategory() == null) || o1.getCategory().equals(o2.getCategory()))
                                return o1.getName().compareTo(o2.getName());
                            return o1.getCategory().compareTo(o2.getCategory());
                        }
                    });
                    int i = 0;
                    for (MetadataIndex index : indexes) {
                        String queryable = index.getQueryable();
                        String name = index.getName();
                        String value = index.getValue();

                        if (value.length() > 50)
                            continue;

                        if (queryable != null)
                            name += "(" + queryable + ")";

                        if (i != 0) {
                            message += "<tr>";
                        }
                        String start = "<td";
                        if (cid == null || i >= 8) {
                            start += " style=\"width: 120px;" + " border-left: 1px solid #205887;\"><td";
                        }
                        i++;
                        message += start + ">" + name + "</td>"
                                + "<td style=\"border-right: 1px solid #205887;\">" + value + "</td>";
                        message += "</tr>";
                    }
                    if (indexes == null || indexes.size() == 0) {
                        message += "</tr>";
                    }
                }
            }
        }
        // No result: next user, no mail.
        if (!atLeastOneResult)
            continue;
        message += "<tr><td colspan=\"3\" style=\"background-color: #205887;" + " height:1px;\" /></tr>";
        message += "</tbody></table><p/>\n";
        message += "You can configure which searches are sent by mail in the " + "<i>saved searches</i> tab in "
                + configurationManager.getNameConfiguration().getShortName()
                + " system at <a target=\"_blank\" href=\""
                + configurationManager.getServerConfiguration().getExternalUrl() + "\">"
                + configurationManager.getServerConfiguration().getExternalUrl()
                + "</a><br/>To stop receiving this message, just disable " + "all searches.<p/>";

        message += "Thanks for using " + configurationManager.getNameConfiguration().getShortName() + ",<br/>"
                + configurationManager.getSupportConfiguration().getName();
        message += "</body></html>";

        logger.info("Sending search results to " + user.getEmail());
        logger.debug(message);

        try {
            he.setHtmlMsg(message);
            mailServer.send(he, user.getEmail(), null, null, "Saved searches notifications");
        } catch (EmailException e) {
            logger.error("Cannot send mail to \"" + user.getEmail() + "\" :" + e.getMessage());
        }
    }
    logger.info(
            "SCHEDULER : User searches mailings done - " + (System.currentTimeMillis() - time_start) + "ms");
}

From source file:br.com.atmatech.sac.controller.Email.java

public void emai(String smtp, String user, String password, Integer porta, Boolean ssl, Boolean tls,
        String emailto, String emailfrom, String conteudo, String assunto)
        throws EmailException, MalformedURLException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtp); // o servidor SMTP para envio do e-mail                  
    email.addTo(emailto);//destinatario            
    conteudo = conteudo.replaceAll("\n", "<p>");
    email.setFrom(emailfrom); // remetente        
    //email.addCc(emailfrom);
    email.setSubject(assunto);/*  ww  w . ja  v a2  s .c  om*/
    // configura a mensagem para o formato HTML        
    email.setHtmlMsg("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"
            + conteudo + "</html>");
    email.setAuthentication(user, password);
    email.setSmtpPort(porta);
    email.setSSL(ssl);
    email.setTLS(tls);
    email.send();
}

From source file:com.cqecom.cms.components.eMailer.TrialOsubEmailController.java

public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    try {/*from   w  ww .ja  va  2  s . c om*/
        String strLicenseName = "";
        String strLicensePassword = "";
        String strLanguageName = "";
        String strEndsAt = "";
        String strLanguageSlug = "";
        String strTrialUrl = "";
        String strOfferPromo = "";
        String strEmailTemplateUrl = "";
        String strFollowupEmailTemplateUrl = "";
        String strEmailSubject = "";
        String strEmailFrom = "";
        String followupEmail = "";
        String strFollowupEmailSubject = "";

        if (request != null) {
            strLicenseName = getParamValue(request, "license_name");
            strLicensePassword = getParamValue(request, "license_password");
            strLanguageName = getParamValue(request, "language_name");
            strEndsAt = getParamValue(request, "ends_at");
            strLanguageSlug = getParamValue(request, "language_slug");
            strTrialUrl = getParamValue(request, "trial_url");
            strOfferPromo = getParamValue(request, "offer_promo");
            strEmailTemplateUrl = getParamValue(request, "email_template_url");
            strFollowupEmailTemplateUrl = getParamValue(request, "followup_email_template_url");
            strEmailSubject = getParamValue(request, "email_subject");
            strFollowupEmailSubject = getParamValue(request, "followup_email_subject");
            strEmailFrom = getParamValue(request, "email_from");
            followupEmail = getParamValue(request, "followup_email");
        }

        if (followupEmail.equals("true")) {
            strEmailTemplateUrl = strFollowupEmailTemplateUrl;
            strEmailSubject = strFollowupEmailSubject;
        }

        session = repository.loginAdministrative(null);
        String pageHtml = session.getRootNode().getNode(strEmailTemplateUrl + "/jcr:content/content")
                .getProperty("text").getValue().getString();

        pageHtml = replaceToken(pageHtml, "license_name", strLicenseName);
        pageHtml = replaceToken(pageHtml, "license_password", strLicensePassword);
        pageHtml = replaceToken(pageHtml, "language_name", strLanguageName);
        pageHtml = replaceToken(pageHtml, "ends_at", strEndsAt);
        pageHtml = replaceToken(pageHtml, "language_slug", strLanguageSlug);
        pageHtml = replaceToken(pageHtml, "trial_url", strTrialUrl);
        pageHtml = replaceToken(pageHtml, "offer_promo", strOfferPromo);
        Email emailObj = new HtmlEmail();
        emailObj.setContent(pageHtml.toString(), "text/html");

        if (!strEmailFrom.equals(""))
            emailObj.setFrom(strEmailFrom, "CqEcom " + strLanguageName + " Trial");

        if (!strLicenseName.equals(""))
            emailObj.addTo(strLicenseName);

        if (!strEmailSubject.equals(""))
            emailObj.setSubject(strEmailSubject);
        ms.sendEmail(emailObj);
        logger.info("Mail sent to => " + strLicenseName);
    } catch (Exception ex) {
        logger.info(ex.getMessage());
    } finally {
        if (session != null)
            session.logout();
    }
}

From source file:com.moss.error_reporting.server.Notifier.java

public void sendEmailNotification(ReportId id, ErrorReport report) {
    try {/* w  ww. j a v  a  2  s.  c om*/
        HtmlEmail email = new HtmlEmail();
        prepEmail(email, id);

        StringBuffer body = new StringBuffer();
        body.append("<html><body>");

        List<ErrorReportChunk> chunks = report.getReportChunks();
        for (int x = 0; x < chunks.size(); x++) {

            ErrorReportChunk chunk = chunks.get(x);
            body.append("<div style=\"padding:5px;text-align:center;border:1px solid black;\">");
            body.append("<span style=\"font-weight:bold;\">" + chunk.getName() + "</span>");
            body.append("<span style=\"font-style:italic;\">[" + chunk.getMimeType() + "</span>]");
            body.append("</div>");
            String mimeType = chunk.getMimeType();
            if (mimeType != null && mimeType.equals("text/plain")) {
                body.append(
                        "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>");
                boolean needsTruncation = chunk.getData().length > MAX_MESSAGE_LENGTH;
                int length = needsTruncation ? MAX_MESSAGE_LENGTH : chunk.getData().length;

                body.append(new String(chunk.getData(), 0, length));
                if (needsTruncation) {
                    body.append("\n");
                    body.append((chunk.getData().length - MAX_MESSAGE_LENGTH) + " more bytes");
                }
                body.append("</pre></div>");
            } else if (mimeType != null && mimeType.equals("application/zip")) {
                body.append(
                        "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>");
                ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(chunk.getData()));
                try {
                    new ZipToTextTool().run(in, body);
                } catch (IOException e) {
                    e.printStackTrace();
                    body.append("Error Reading Zip:" + e.getMessage());
                }
                body.append("</pre></div>");
            }
            if (x != chunks.size() - 1 && chunks.size() > 1)
                body.append("<br/><br/>");

        }
        body.append("</body></html>");

        //         email.setHtmlMsg("<html><body>Hello World</body></html>");
        email.setHtmlMsg(body.toString());
        //         email.setTextMsg("HTML EMAIL");
        email.buildMimeMessage();
        email.sendMimeMessage();

    } catch (EmailException e) {
        e.printStackTrace();
    }
}

From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTP.java

public ConfigurazioneSMTP() {

    this.setMargin(true);

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);//from  w w w .  j av  a  2 s  .  c o  m
    TextField smtpPort = new TextField("SMTP Port");
    smtpPort.setRequired(true);
    TextField smtpUser = new TextField("SMTP Username");
    smtpUser.setRequired(true);
    TextField smtpPwd = new TextField("SMTP Password");
    smtpPwd.setRequired(true);
    TextField pwdConf = new TextField("Conferma la Password");
    pwdConf.setRequired(true);
    CheckBox security = new CheckBox("Sicurezza del server");

    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        System.out.println("Carico file di configurazione");
        try {
            props.load(config);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    smtpHost.setValue(props.getProperty("smtp_host"));
    smtpUser.setValue(props.getProperty("smtp_user"));
    security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec")));

    Button salva = new Button("Salva i parametri");
    salva.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Salvo i parametri SMTP");
        if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid()
                && smtpPwd.getValue().equals(pwdConf.getValue())) {
            props.setProperty("smtp_host", smtpHost.getValue());
            props.setProperty("smtp_port", smtpPort.getValue());
            props.setProperty("smtp_user", smtpUser.getValue());
            props.setProperty("smtp_pwd", smtpPwd.getValue());
            props.setProperty("smtp_sec", security.getValue().toString());
            String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext()
                    .getRealPath("WEB-INF");
            File f = new File(webInfPath + "/config.properties");
            try {
                OutputStream o = new FileOutputStream(f);
                try {
                    props.store(o, "Prova");
                } catch (IOException ex) {
                    Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            Notification.show("Parametri salvati");
        } else {
            Notification.show("Ricontrolla i parametri");
        }

    });

    TextField emailTest = new TextField("Destinatario Mail di Prova");
    emailTest.setImmediate(true);
    emailTest.addValidator(new EmailValidator("Mail non valida"));

    Button test = new Button("Invia una mail di prova");
    test.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Invio della mail di prova");
        if (emailTest.isValid()) {
            try {
                System.out.println("Invio mail di prova a " + emailTest.getValue());
                HtmlEmail email = new HtmlEmail();
                email.setHostName(props.getProperty("smtp_host"));
                email.setSmtpPort(Integer.parseInt(props.getProperty("smtp_port")));
                email.setSSLOnConnect(Boolean.parseBoolean(props.getProperty("smtp_sec")));
                email.setAuthentication(props.getProperty("smtp_user"), props.getProperty("smtp_pwd"));
                email.setFrom("prova@prova.it");
                email.setSubject("Mail di prova");
                email.addTo(emailTest.getValue());
                email.setHtmlMsg("This is the message");
                email.send();
            } catch (EmailException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            Notification.show("Controlla l'indirizzo mail del destinatario");
        }
    });

    this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test);

}

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

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {/*from  w w  w .j a va2  s  . c o  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(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:com.jredrain.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(0);// w  w  w .j a  va2  s. co m
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;
    try {
        log.setType(RedRain.MsgType.EMAIL.getValue());
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("redrain");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {

        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));

            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);
            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(RedRain.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    }

}

From source file:com.enseval.ttss.util.MailNotif.java

public void emailTolakUpdate(Giro gironya) {

    String port = (Executions.getCurrent().getServerPort() == 80) ? ""
            : (":" + Executions.getCurrent().getServerPort());
    String url = Executions.getCurrent().getScheme() + "://" + Executions.getCurrent().getServerName() + port
            + Executions.getCurrent().getContextPath() + "/info_giro.zul";

    String msg = "<html>" + "<head>"
            + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
            + "<title>Untitled Document</title>" + "<style type=\"text/css\">" + "p {"
            + "font-family: \"Courier New\", Courier, monospace;" + "font-size: 12px;" + "}" + "</style>"
            + "</head>" + "<p>Yth, </p>"
            + "<p>Berikut kami informasikan giro tolakan berikut sudah di proses kliring ulang;</p> " + "<br/>"
            + "<p><pre>" + "Customer ID      : " + gironya.getCustomer().getId() + "<br/>"
            + "Nama Customer    : " + gironya.getCustomer().getNama() + "<br/>" + "Nomor Giro       : "
            + gironya.getNomorGiro() + "<br/>" + "Nilai            : " + Rupiah.format(gironya.getNilai())
            + "<br/>" + "Bank             : " + gironya.getBank() + "<br/>" + "Tgl Kliring      : "
            + gironya.getTglKliring() + "<br/>" + "Keterangan       : " + gironya.getKeterangan() + "" + "<pre>"
            + "</p>" + "<br/>" + "<br/>" + "<br/>"
            + "<p>Jika tidak ada tolakan, account shipto customer akan segera diaktifkan oleh bagian Data Proses.</p>"
            + "<br/>" + "<br/>" + "<p><i>Note : " + "<br>" + "Info giro " + url + "<br/>"
            + "Ini adalah email otomatis, mohon tidak membalas email ini !</i></p>" + "</html>";

    try {//from   ww w .  ja v  a2 s.  co  m
        HtmlEmail mail = new HtmlEmail();
        mail.setHostName(Util.setting("smtp_host"));
        mail.setSmtpPort(Integer.parseInt(Util.setting("smtp_port")));
        mail.setAuthenticator((Authenticator) new DefaultAuthenticator(Util.setting("smtp_username"),
                Util.setting("smtp_password")));
        mail.setFrom(Util.setting("email_from"));
        for (String s : Util.setting("email_to").split(",")) {
            mail.addTo(s.trim());
        }

        mail.setSubject("[INFO GIRO TOLAK - Update] - Nomor Giro : " + gironya.getNomorGiro() + " , Customer : "
                + gironya.getCustomer().getNama() + " (" + gironya.getCustomer().getId() + ")");
        mail.setHtmlMsg(msg);
        mail.send();
    } catch (EmailException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }

}