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

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

Introduction

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

Prototype

public HtmlEmail setHtmlMsg(final String aHtml) throws EmailException 

Source Link

Document

Set the HTML content.

Usage

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

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSearchesCronConfiguration().isActive())
        return;/*from ww  w . j  a  va2s  . co  m*/
    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:email.cadastro.EmailCadastro.java

public boolean EnviarCodConfirmacao(String codigo, String emailCadastro) {
    HtmlEmail email = new HtmlEmail();
    email.setSSLOnConnect(true);//w  w  w . j a v a  2s .com
    email.setHostName("smtp.gmail.com");
    //email.setSslSmtpPort("465");
    email.setAuthenticator(new DefaultAuthenticator("contatogamesapp@gmail.com", "gamesifsul"));
    try {
        email.setFrom("contatogamesapp@gmail.com", "Equipe GamesApp");
        email.setDebug(true);
        email.setSubject("Cdigo de confirmao");

        String emailHtml = "<!doctype html><html><head><meta charset=\"UTF-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Email</title></head><style type=\"text/css\">p{margin:10px 0;padding:0;}table{border-collapse:collapse;}h1,h2,h3,h4,h5,h6{display:block;margin:0;padding:0;}img,a img{border:0;height:auto;outline:none;text-decoration:none;}body,#bodyTable,#bodyCell{height:100%;margin:0;padding:0;width:100%;}#outlook a{padding:0;}img{-ms-interpolation-mode:bicubic;}table{mso-table-lspace:0pt;mso-table-rspace:0pt;}.ReadMsgBody{width:100%;}.ExternalClass{width:100%;}p,a,li,td,blockquote{mso-line-height-rule:exactly;}a[href^=tel],a[href^=sms]{color:inherit;cursor:default;text-decoration:none;}p,a,li,td,body,table,blockquote{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;}.ExternalClass,.ExternalClass p,.ExternalClass td,.ExternalClass div,.ExternalClass span,.ExternalClass font{line-height:100%;}a[x-apple-data-detectors]{color:inherit !important;text-decoration:none !important;font-size:inherit !important;font-family:inherit !important;font-weight:inherit !important;line-height:inherit !important;}#bodyCell{padding:10px;}.templateContainer{max-width:600px !important;}a.mcnButton{display:block;}.mcnImage{vertical-align:bottom;}.mcnTextContent{word-break:break-word;}.mcnTextContent img{height:auto !important;}.mcnDividerBlock{table-layout:fixed !important;}body,#bodyTable{background-color:#FAFAFA;}#bodyCell{border-top:0;}.templateContainer{border:0;}h1{color:#616161;font-family:Helvetica;font-size:22px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:normal;text-align:left;}h2{color:#202020;font-family:Helvetica;font-size:22px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:normal;text-align:left;}h3{color:#202020;font-family:Helvetica;font-size:20px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:normal;text-align:left;}h4{color:#202020;font-family:Helvetica;font-size:18px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:normal;text-align:left;}#templatePreheader{background-color:#FAFAFA;border-top:0;border-bottom:0;padding-top:20px;padding-bottom:20px;}#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{color:#656565;font-family:Helvetica;font-size:12px;line-height:150%;text-align:left;}#templatePreheader .mcnTextContent a,#templatePreheader .mcnTextContent p a{color:#656565;font-weight:normal;text-decoration:underline;}#templateHeader{background-color:#FFFFFF;border-top:0;border-bottom:0;padding-top:9px;padding-bottom:0;}#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{color:#202020;font-family:Helvetica;font-size:16px;line-height:150%;text-align:left;}#templateHeader .mcnTextContent a,#templateHeader .mcnTextContent p a{color:#2BAADF;font-weight:normal;text-decoration:underline;}#templateBody{background-color:#FFFFFF;border-top:0;border-bottom:2px solid #EAEAEA;padding-top:0;padding-bottom:9px;}#templateBody .mcnTextContent,#templateBody .mcnTextContent p{color:#616161;font-family:Helvetica;font-size:16px;line-height:150%;text-align:left;}#templateBody .mcnTextContent a,#templateBody .mcnTextContent p a{color:#2BAADF;font-weight:normal;text-decoration:underline;}#templateFooter{background-color:#FAFAFA;border-top:0;border-bottom:0;padding-top:9px;padding-bottom:9px;}#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{color:#656565;font-family:Helvetica;font-size:12px;line-height:150%;text-align:center;}#templateFooter .mcnTextContent a,#templateFooter .mcnTextContent p a{color:#656565;font-weight:normal;text-decoration:underline;}button{background: #107a49; border: none; padding: 10px 20px; border-radius: 70px; color: #fff;margin-top: 30px;cursor: pointer;}@media only screen and (min-width:768px){.templateContainer{width:600px !important;}}@media only screen and (max-width: 480px){body,table,td,p,a,li,blockquote{-webkit-text-size-adjust:none !important;}}@media only screen and (max-width: 480px){body{width:100% !important;min-width:100% !important;}}@media only screen and (max-width: 480px){#bodyCell{padding-top:10px !important;}}@media only screen and (max-width: 480px){.mcnImage{width:100% !important;}}@media only screen and (max-width: 480px){.mcnCartContainer,.mcnCaptionTopContent,.mcnRecContentContainer,.mcnCaptionBottomContent,.mcnTextContentContainer,.mcnBoxedTextContentContainer,.mcnImageGroupContentContainer,.mcnCaptionLeftTextContentContainer,.mcnCaptionRightTextContentContainer,.mcnCaptionLeftImageContentContainer,.mcnCaptionRightImageContentContainer,.mcnImageCardLeftTextContentContainer,.mcnImageCardRightTextContentContainer{max-width:100% !important;width:100% !important;}}@media only screen and (max-width: 480px){.mcnBoxedTextContentContainer{min-width:100% !important;}}@media only screen and (max-width: 480px){.mcnImageGroupContent{padding:9px !important;}}@media only screen and (max-width: 480px){.mcnCaptionLeftContentOuter .mcnTextContent,.mcnCaptionRightContentOuter .mcnTextContent{padding-top:9px !important;}}@media only screen and (max-width: 480px){.mcnImageCardTopImageContent,.mcnCaptionBlockInner .mcnCaptionTopContent:last-child .mcnTextContent{padding-top:18px !important;}}@media only screen and (max-width: 480px){.mcnImageCardBottomImageContent{padding-bottom:9px !important;}}@media only screen and (max-width: 480px){.mcnImageGroupBlockInner{padding-top:0 !important;padding-bottom:0 !important;}}@media only screen and (max-width: 480px){.mcnImageGroupBlockOuter{padding-top:9px !important;padding-bottom:9px !important;}}@media only screen and (max-width: 480px){.mcnTextContent,.mcnBoxedTextContentColumn{padding-right:18px !important;padding-left:18px !important;}}@media only screen and (max-width: 480px){.mcnImageCardLeftImageContent,.mcnImageCardRightImageContent{padding-right:18px !important;padding-bottom:0 !important;padding-left:18px !important;}}@media only screen and (max-width: 480px){.mcpreview-image-uploader{display:none !important;width:100% !important;}}@media only screen and (max-width: 480px){h1{font-size:22px !important;line-height:125% !important;}}@media only screen and (max-width: 480px){h2{font-size:20px !important;line-height:125% !important;}}@media only screen and (max-width: 480px){h3{font-size:18px !important;line-height:125% !important;}}@media only screen and (max-width: 480px){h4{font-size:16px !important;line-height:150% !important;}}@media only screen and (max-width: 480px){.mcnBoxedTextContentContainer .mcnTextContent,.mcnBoxedTextContentContainer .mcnTextContent p{font-size:14px !important;line-height:150% !important;}}@media only screen and (max-width: 480px){#templatePreheader{display:block !important;}}@media only screen and (max-width: 480px){#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{font-size:14px !important;line-height:150% !important;}}@media only screen and (max-width: 480px){#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{font-size:16px !important;line-height:150% !important;}}@media only screen and (max-width: 480px){#templateBody .mcnTextContent,#templateBody .mcnTextContent p{font-size:16px !important;line-height:150% !important;}}@media only screen and (max-width: 480px){#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{font-size:14px !important;line-height:150% !important;}}</style><body><center><table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"100%\" width=\"100%\" id=\"bodyTable\"><tr><td align=\"center\" valign=\"top\" id=\"bodyCell\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"templateContainer\"><tr><td valign=\"top\" id=\"templatePreheader\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnImageBlock\" style=\"min-width:100%;\"><tbody class=\"mcnImageBlockOuter\"><tr><td valign=\"top\" style=\"padding:9px\" class=\"mcnImageBlockInner\"><table align=\"left\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"mcnImageContentContainer\" style=\"min-width:100%;\"><tbody><tr><td class=\"mcnImageContent\" valign=\"top\" style=\"padding-right: 9px; padding-left: 9px; padding-top: 0; padding-bottom: 0;\"><a href=\"https://github.com/GamesApp\" target=\"_blank\"><img align=\"left\" alt=\"\" src=\"https://ap.imagensbrasil.org/images/2016/11/21/logo_escrita.png\" width=\"200\" style=\"max-width:200px; padding-bottom: 0; display: inline !important; vertical-align: bottom;\" class=\"mcnImage\"></a></td></tr></tbody></table></td></tr></tbody></table></td></tr><tr><td valign=\"top\" id=\"templateBody\" style=\"border-radius:5px;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnTextBlock\" style=\"min-width:100%;\"><tbody class=\"mcnTextBlockOuter\"><tr><td valign=\"top\" class=\"mcnTextBlockInner\" style=\"padding-top:9px;\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:100%; min-width:100%;\" width=\"100%\" class=\"mcnTextContentContainer\"><tbody><tr><td valign=\"top\" class=\"mcnTextContent\" style=\"padding-top:30px; padding-right:30px; padding-bottom:30px; padding-left:30px;\"><h1>Cdigo de confirmao</h1><p>E a, tudo certo?!</p><p>Recebemos uma solicitao de cadastro no aplicativo GamesApp.</p><p>Segue o cdigo de confirmao:</p><div style=\"background: #CCCCCC; text-align: center; border-radius:5px; padding-top: 9px; padding-bottom: 9px;\">"
                + codigo
                + "</div><p style=\"font-size: 10px; \">Obs.: Se voc no realizou est operao entrar em contato o mais rpido possvel!</p></td></tr></tbody></table></td></tr></tbody></table><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnDividerBlock\" style=\"min-width:100%;\"><tbody class=\"mcnDividerBlockOuter\"><tr><td class=\"mcnDividerBlockInner\" style=\"min-width:100%; padding:18px 30px;\"><table class=\"mcnDividerContent\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width: 100%;border-top: 2px dashed #EAEAEA;\"><tbody><tr><td><span></span></td></tr></tbody></table></td></tr></tbody></table><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnFollowBlock\" style=\"min-width:100%;\"><tbody class=\"mcnFollowBlockOuter\"><tr><td align=\"center\" valign=\"top\" style=\"padding:9px\" class=\"mcnFollowBlockInner\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnFollowContentContainer\" style=\"min-width:100%;\"><tbody><tr><td align=\"center\" style=\"padding-left:9px;padding-right:9px;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"min-width:100%;\" class=\"mcnFollowContent\"><tbody><tr><td align=\"center\" valign=\"top\" style=\"padding-top:9px; padding-right:9px; padding-left:9px;\"><table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td align=\"center\" valign=\"top\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"display:inline;\"><tbody><tr><td valign=\"top\" style=\"padding-right:0; padding-bottom:9px;\" class=\"mcnFollowContentItemContainer\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnFollowContentItem\"><tbody><tr><td align=\"left\" valign=\"middle\" style=\"padding-top:5px; padding-right:10px; padding-bottom:5px; padding-left:9px;\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"\"><tbody><tr><td align=\"center\" valign=\"middle\" width=\"24\" class=\"mcnFollowIconContent\"><a href=\"https://github.com/GamesApp\" target=\"_blank\"><img src=\"http://oi63.tinypic.com/30sk57c.jpg\" style=\"display:block;\" height=\"24\" width=\"24\" class=\"\"></a></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr><tr><td valign=\"top\" id=\"templateFooter\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" class=\"mcnTextBlock\" style=\"min-width:100%;\"><tbody class=\"mcnTextBlockOuter\"><tr><td valign=\"top\" class=\"mcnTextBlockInner\" style=\"padding-top:9px;\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:100%; min-width:100%;\" width=\"100%\" class=\"mcnTextContentContainer\"><tbody><tr><td valign=\"top\" class=\"mcnTextContent\" style=\"padding-top:0; padding-right:18px; padding-bottom:9px; padding-left:18px;\"><em> GamesApp. Todos os direitos reservados.&nbsp;</em><br><br></td></tr></tbody></table></td></tr></tbody></table></td></tr></table></td></tr></table></center></body></html>";
        email.setHtmlMsg(emailHtml);
        email.addTo(emailCadastro);
        email.send();
    } catch (EmailException e) {
        return false;
    }
    return true;
}

From source file:net.wildpark.dswp.supports.MailService.java

public boolean sendEmail(String to, String textBody) {
    try {//  w ww.ja  v a  2 s  .co m
        HtmlEmail email = new HtmlEmail();
        email.setCharset("utf-8");
        email.setHostName("mail.wildpark.net");
        email.setSmtpPort(25);
        email.setAuthenticator(new DefaultAuthenticator("informer@mksat.net", "22v5C728"));
        email.setFrom("informer@mksat.net");
        email.setSubject("Automatic message from darkside.wildpark.net");
        email.setHtmlMsg(textBody);
        email.addTo(to);
        email.send();
        logFacade.create(new Log("Sended mail " + to));
    } catch (EmailException ex) {
        logFacade.create(new Log("Error with mail sending", ex, LoggerLevel.ERROR));
        System.out.println(ex);
        return false;
    }
    return true;
}

From source file:org.apache.unomi.plugins.mail.actions.SendMailAction.java

public int execute(Action action, Event event) {
    String from = (String) action.getParameterValues().get("from");
    String to = (String) action.getParameterValues().get("to");
    String cc = (String) action.getParameterValues().get("cc");
    String bcc = (String) action.getParameterValues().get("bcc");
    String subject = (String) action.getParameterValues().get("subject");
    String template = (String) action.getParameterValues().get("template");

    ST stringTemplate = new ST(template);
    stringTemplate.add("profile", event.getProfile());
    stringTemplate.add("event", event);
    // load your HTML email template
    String htmlEmailTemplate = stringTemplate.render();

    // define you base URL to resolve relative resource locations
    try {//from  w  w  w . j  ava  2  s.c  om
        new URL("http://www.apache.org");
    } catch (MalformedURLException e) {
        //
    }

    // create the email message
    HtmlEmail email = new ImageHtmlEmail();
    // email.setDataSourceResolver(new DataSourceResolverImpl(url));
    email.setHostName(mailServerHostName);
    email.setSmtpPort(mailServerPort);
    email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword));
    email.setSSLOnConnect(mailServerSSLOnConnect);
    try {
        email.addTo(to);
        email.setFrom(from);
        if (cc != null && cc.length() > 0) {
            email.addCc(cc);
        }
        if (bcc != null && bcc.length() > 0) {
            email.addBcc(bcc);
        }
        email.setSubject(subject);

        // set the html message
        email.setHtmlMsg(htmlEmailTemplate);

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

        // send the email
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send mail", e);
    }

    return EventService.NO_CHANGE;
}

From source file:org.camunda.bpm.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected HtmlEmail createHtmlEmail(String text, String html) {
    HtmlEmail email = new HtmlEmail();
    try {//from ww  w  .j ava  2  s .  c o m
        email.setHtmlMsg(html);
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        return email;
    } catch (EmailException e) {
        throw new ProcessEngineException("Could not create HTML email", e);
    }
}

From source file:org.cerberus.service.email.impl.sendMail.java

public static void sendHtmlMail(String host, int port, String body, String subject, String from, String to,
        String cc) throws Exception {

    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(port);/*  w  ww .  j  a v a2 s . c o  m*/
    email.setDebug(false);
    email.setHostName(host);
    email.setFrom(from);
    email.setSubject(subject);
    email.setHtmlMsg(body);

    String[] destinataire = to.split(";");

    for (int i = 0; i < destinataire.length; i++) {
        String name;
        String emailaddress;
        if (destinataire[i].contains("<")) {
            String[] destinatairedata = destinataire[i].split("<");
            name = destinatairedata[0].trim();
            emailaddress = destinatairedata[1].replace(">", "").trim();
        } else {
            name = "";
            emailaddress = destinataire[i];
        }
        email.addTo(emailaddress, name);
    }

    String[] copy = cc.split(";");

    for (int i = 0; i < copy.length; i++) {
        String namecc;
        String emailaddresscc;
        if (copy[i].contains("<")) {
            String[] copydata = copy[i].split("<");
            namecc = copydata[0].trim();
            emailaddresscc = copydata[1].replace(">", "").trim();
        } else {
            namecc = "";
            emailaddresscc = copy[i];
        }
        email.addCc(emailaddresscc, namecc);
    }

    email.setTLS(true);

    email.send();

}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a HTML message.//from  w  w  w. j a va 2s . c om
 *
 * @param headers    the mail headers
 * @param htmlBody   the mail body (HTML based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendHtmlMail(MailMessageHeaders headers, String htmlBody, DataSource... dataSources) {
    try {
        HtmlEmail email = new HtmlEmail();

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        if (dataSources != null) {
            for (DataSource dataSource : dataSources)
                email.attach(dataSource, dataSource.getName(), dataSource.getName());
        }

        email.setCharset(headers.getCharset());
        email.setHtmlMsg(htmlBody);

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.cobbzilla.mail.sender.SmtpMailSender.java

private Email constructEmail(SimpleEmailMessage message) throws EmailException {
    final Email email;
    if (message instanceof ICalEvent) {
        final MultiPartEmail multiPartEmail = new MultiPartEmail();

        ICalEvent iCalEvent = (ICalEvent) message;

        // Calendar iCalendar = new Calendar();
        Calendar iCalendar = ICalUtil.newCalendarEvent(iCalEvent.getProdId(), iCalEvent);
        byte[] attachmentData = ICalUtil.toBytes(iCalendar);

        String icsName = iCalEvent.getIcsName() + ".ics";
        String contentType = "text/calendar; icsName=\"" + icsName + "\"";
        try {/*from   w w w.j  a  va2 s.  com*/
            multiPartEmail.attach(new ByteArrayDataSource(attachmentData, contentType), icsName, "",
                    EmailAttachment.ATTACHMENT);
        } catch (IOException e) {
            throw new EmailException("constructEmail: couldn't attach: " + e, e);
        }
        email = multiPartEmail;

    } else if (message.getHasHtmlMessage()) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setTextMsg(message.getMessage());
        htmlEmail.setHtmlMsg(message.getHtmlMessage());
        email = htmlEmail;

    } else {
        email = new SimpleEmail();
        email.setMsg(message.getMessage());
    }
    return email;
}

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

/**
 * Send an html mail. Will look on the settings directly to know the
 * remitent// w  ww  .j  a  va2  s .  c o m
 *
 * @param toAddress
 * @param subject
 * @param htmlMessage
 * @param settings
 * @throws EmailException
 */
public static Boolean sendHtmlMail(List<String> toAddress, String subject, String htmlMessage,
        SettingManager settings) {
    // Create data information to compose the mail
    HtmlEmail email = new HtmlEmail();
    configureBasics(settings, email);

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

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

    return send(email);
}

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

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

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

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

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

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

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

    return send(email);
}