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

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

Introduction

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

Prototype

public String embed(final File file) throws EmailException 

Source Link

Document

Embeds a file in the HTML.

Usage

From source file:edu.wright.cs.fa15.ceg3120.concon.server.EmailManager.java

/**
 * Composes the message using the body inside of an HTML template with a logo image.
 * @param mail The outgoing email to compose.
 * @param body The body text to add./*from  www  .  j  a v a 2 s .  co  m*/
 * @return The HTML output.
 * @throws EmailException Exception from embedding image into message.
 */
private String composeAsHtml(HtmlEmail mail, String body) throws EmailException {
    StringBuffer msg = new StringBuffer();
    File logoImage = new File(props.getProperty("logo_image_location"));
    msg.append("<html><body>");
    msg.append("<img src=cid:").append(mail.embed(logoImage)).append(">");
    msg.append("<br>");
    msg.append(body);
    msg.append("</body></html>");
    return msg.toString();
}

From source file:br.com.asisprojetos.email.SendEmail.java

public void enviar(String toEmail[], String subject, String templateFile, List<String> fileNames, String mes,
        int codContrato) {

    try {/*  w  w w.  j  av a  2 s.  c o  m*/

        String htmlFileTemplate = loadHtmlFile(templateFile);

        for (String to : toEmail) {

            String htmlFile = htmlFileTemplate;

            // Create the email message
            HtmlEmail email = new HtmlEmail();
            email.setHostName(config.getHostname());
            email.setSmtpPort(config.getPort());
            email.setFrom(config.getFrom(), config.getFromName()); // remetente
            email.setAuthenticator(
                    new DefaultAuthenticator(config.getAuthenticatorUser(), config.getAuthenticatorPassword()));
            email.setSSL(true);
            email.setSubject(subject); //Assunto

            email.addTo(to);//para

            logger.debug("Enviando Email para : [{}] ", to);

            int i = 1;

            for (String fileName : fileNames) {

                String cid;

                if (fileName.startsWith("diagnostico")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph24$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de diagnostico nao encontrado.");
                    }
                } else if (fileName.startsWith("recorrencia")) {
                    try {
                        cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                        htmlFile = StringUtils.replace(htmlFile, "$codGraph25$",
                                "<img src=\"cid:" + cid + "\">");
                    } catch (EmailException ex) {
                        logger.error("Arquivo de recorrencia nao encontrado.");
                    }
                } else {
                    cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));
                    htmlFile = StringUtils.replace(htmlFile, "$codGraph" + i + "$",
                            "<img src=\"cid:" + cid + "\">");
                    i++;
                }

            }

            //apaga $codGraph$ no usado do template
            for (int t = i; t <= 25; t++) {
                htmlFile = StringUtils.replace(htmlFile, "$codGraph" + t + "$", " ");
            }

            htmlFile = StringUtils.replace(htmlFile, "$MES$", mes);
            htmlFile = StringUtils.replace(htmlFile, "$MAIL$", to);
            htmlFile = StringUtils.replace(htmlFile, "$CONTRATO$", Integer.toString(codContrato));

            email.setHtmlMsg(htmlFile);

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

            // send the email
            email.send();

        }

        logger.debug("Email enviado com sucesso......");

    } catch (FileNotFoundException ex) {
        logger.error("Arquivo [{}/{}] nao encontrado para leitura.", config.getHtmlDirectory(), templateFile);
    } catch (Exception ex) {
        logger.error("Erro ao Enviar email : {}", ex);
    }

}

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

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSearchesCronConfiguration().isActive())
        return;//from   w  w w. j a v  a2  s .c o 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:org.jkandasa.email.blaster.EmailUtils.java

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

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

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

From source file:org.xerela.server.birt.ReportJob.java

/**
 * Email the report if the JobData defines the required parameters,
 * otherwise this method just returns without doing anything.
 *
 * @param intermediate the BIRT intermediate format file
 * @param executionContext the Quartz JobExecutionContext of this job
 *//*www .j  a  v a  2 s  . c o m*/
@SuppressWarnings("nls")
private void emailReport(File intermediate, JobExecutionContext executionContext) {
    JobDataMap jobData = executionContext.getMergedJobDataMap();
    boolean emailAttachment = jobData.containsKey(REPORT_EMAIL_ATTACHMENT)
            ? jobData.getBooleanValue(REPORT_EMAIL_ATTACHMENT)
            : false;
    boolean emailLink = jobData.containsKey(REPORT_EMAIL_LINK) ? jobData.getBooleanValue(REPORT_EMAIL_LINK)
            : false;
    String emailTo = jobData.getString(REPORT_EMAIL_TO);
    String emailCc = jobData.getString(REPORT_EMAIL_CC);
    String reportFormat = jobData.getString(REPORT_EMAIL_FORMAT);

    if (!validateEmailProperties(emailAttachment, emailLink, emailTo, reportFormat)) {
        return;
    }

    try {
        Email email = null;
        if (reportFormat.equals("pdf")) {
            email = new MultiPartEmail();
        } else if (reportFormat.equals("html")) {
            email = new HtmlEmail();
        }

        setupEmail(executionContext, emailTo, emailCc, email);

        // Create the attachment
        if (emailAttachment) {
            final File render = RenderElf.render(intermediate, executionData.getId(), reportFormat);

            if (reportFormat.equals("pdf")) {
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(render.getAbsolutePath());
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setDescription(reportTitle);
                attachment.setName(String.format("%s.%s", reportTitle, reportFormat)); //$NON-NLS-1$
                ((MultiPartEmail) email).attach(attachment);
            } else if (reportFormat.equals("html")) {
                HtmlEmail htmlEmail = (HtmlEmail) email;
                String html = stringFromFile(render);

                final String pathStub = render.getName().replaceFirst("\\.[a-z]+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
                File parentDir = new File(render.getParent());
                File[] listFiles = parentDir.listFiles(new FileFilter() {
                    public boolean accept(File pathname) {
                        return pathname.getName().startsWith(pathStub) && !pathname.getName().endsWith("html"); //$NON-NLS-1$
                    }
                });

                for (File image : listFiles) {
                    String cid = htmlEmail.embed(image);
                    String regex = "src=.+" + image.getName();
                    html = html.replaceAll(regex, "src=\"cid:" + cid);
                }

                htmlEmail.setHtmlMsg(html);
            }
        }

        if (emailLink) {
        }

        email.send();
    } catch (AddressException ae) {
        LOGGER.error(Messages.bind(Messages.ReportJob_badAddresses, reportTitle), ae);
    } catch (EmailException ee) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ee);
    } catch (EngineException ee) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ee);
    } catch (IOException ie) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ie);
    }
}