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.asisprojetos.email.SendEmail.java

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

    try {/*from www  .jav  a2 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:com.aquest.emailmarketing.web.service.SendEmail.java

/**
 * Send email./*from ww w  . j  ava 2 s . co  m*/
 *
 * @param broadcast the broadcast
 * @param emailConfig the email config
 * @param emailList the email list
 * @throws EmailException the email exception
 * @throws MalformedURLException the malformed url exception
 * @throws InterruptedException the interrupted exception
 */
@Async
public void sendEmail(Broadcast broadcast, EmailConfig emailConfig, EmailList emailList)
        throws EmailException, MalformedURLException, InterruptedException {

    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    // email configuration part
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(emailConfig.getPort());
    email.setHostName(emailConfig.getHostname());
    email.setAuthenticator(new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword()));
    email.setSSLOnConnect(emailConfig.isSslonconnect());
    email.setDebug(emailConfig.isDebug());
    email.setFrom(emailConfig.getFrom_address()); //ovde dodati i email from description

    System.out.println(emailList);
    HashMap<String, String> variables = processVariableService.ProcessVariable(emailList);

    for (String keys : variables.keySet()) {
        System.out.println("key:" + keys + ", value:" + variables.get(keys));
    }

    String processSubject = broadcast.getSubject();
    String newHtml = broadcast.getHtmlbody_embed();
    String newPlainText = broadcast.getPlaintext();

    for (String key : variables.keySet()) {
        processSubject = processSubject.replace("[" + key + "]", variables.get(key));
        System.out.println(key + "-" + variables.get(key));
        newHtml = newHtml.replace("[" + key + "]", variables.get(key));
        newPlainText = newPlainText.replace("[" + key + "]", variables.get(key));
    }
    System.out.println(processSubject);
    email.setSubject(processSubject);
    email.addTo(emailList.getEmail());

    String image = embeddedImageService.getEmbeddedImages(broadcast.getBroadcast_id()).getUrl();
    List<String> images = Arrays.asList(image.split(";"));
    for (int j = 0; j < images.size(); j++) {
        System.out.println(images.get(j));
    }
    for (int i = 0; i < images.size(); i++) {
        String id = email.embed(images.get(i), "Slika" + i);
        newHtml = newHtml.replace("[IMAGE:" + i + "]", "cid:" + id);
    }

    Config config = configService.getConfig("trackingurl");
    //DONE: Create jsp page for tracking server url
    String serverUrl = config.getValue();
    System.out.println(serverUrl);
    Base64 base64 = new Base64(true);

    Pattern pattern = Pattern.compile("<%tracking=(.*?)=tracking%>");
    Matcher matcher = pattern.matcher(newHtml);
    while (matcher.find()) {
        String url = matcher.group(1);
        System.out.println(url);
        logger.debug(url);
        String myEncryptedUrl = new String(base64.encode(url.getBytes()));

        String oldurl = "<%tracking=" + url + "=tracking%>";
        logger.debug(oldurl);
        System.out.println(oldurl);
        String newurl = serverUrl + "tracking?id=" + myEncryptedUrl;
        logger.debug(newurl);
        System.out.println(newurl);
        newHtml = newHtml.replace(oldurl, newurl);
    }
    //        System.out.println(newHtml);

    email.setHtmlMsg(newHtml);
    email.setTextMsg(newPlainText);
    try {
        System.out.println("A ovo ovde?");
        email.send();
        emailList.setStatus("SENT");
        emailList.setProcess_dttm(curTimestamp);
        emailListService.SaveOrUpdate(emailList);
    } catch (Exception e) {
        logger.error(e);
    }
    // time in seconds to wait between 2 mails
    TimeUnit.SECONDS.sleep(emailConfig.getWait());
}

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 .ja v a 2s. 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 www  .  java 2  s . c om*/
        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.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 {//  www. j  a  v  a  2  s. c o m
            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.flowable.engine.impl.bpmn.behavior.MailActivityBehavior.java

protected HtmlEmail createHtmlEmail(String text, String html) {
    HtmlEmail email = new HtmlEmail();
    try {/*from  w  w w . j av a2s  . c om*/
        email.setHtmlMsg(html);
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        return email;
    } catch (EmailException e) {
        throw new FlowableException("Could not create HTML email", e);
    }
}

From source file:org.gravidence.gravifon.email.ApacheCommonsEmailSender.java

@Override
public boolean send(String toAddress, String toName, String subject, String htmlMessage, String textMessage) {
    HtmlEmail email = new HtmlEmail();

    email.setHostName(host);//from   w ww . j  ava2  s  . c om
    email.setSslSmtpPort(port);
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    email.setSSLOnConnect(true);

    try {
        if (StringUtils.isBlank(toName)) {
            email.addTo(toAddress);
        } else {
            email.addTo(toAddress, toName);
        }
        email.setFrom(fromAddress, fromName);

        email.setSubject(subject);

        if (htmlMessage != null) {
            email.setHtmlMsg(htmlMessage);
        }
        if (textMessage != null) {
            email.setTextMsg(textMessage);
        }

        email.send();
    } catch (EmailException ex) {
        // TODO think about throwing GravifonException
        LOGGER.warn(String.format("Failed to send an email to %s", toAddress), ex);

        return false;
    }

    return true;
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email./*from  www  .j  ava  2s .  c om*/
 * @param to the recipient of the email.
 * @param subject the subject of the email.
 * @param content the body of the email.
 * @throws SystemException if the email couldn't be sent due to some mail server exception.
 */
public void sendHTML(String from, String to, String cc, String bcc, String bounceAddress, String replyTo,
        String subject, String content, String encoding) throws SystemException {
    try {
        HtmlEmail email = new HtmlEmail();
        String mailServer = CmsPropertyHandler.getMailSmtpHost();
        String mailPort = CmsPropertyHandler.getMailSmtpPort();
        String systemEmailSender = CmsPropertyHandler.getSystemEmailSender();

        email.setHostName(mailServer);
        if (mailPort != null && !mailPort.equals(""))
            email.setSmtpPort(Integer.parseInt(mailPort));

        boolean needsAuthentication = false;
        try {
            needsAuthentication = new Boolean(CmsPropertyHandler.getMailSmtpAuth()).booleanValue();
        } catch (Exception ex) {
            needsAuthentication = false;
        }

        if (needsAuthentication) {
            final String userName = CmsPropertyHandler.getMailSmtpUser();
            final String password = CmsPropertyHandler.getMailSmtpPassword();

            email.setAuthentication(userName, password);
        }

        email.setBounceAddress(systemEmailSender);
        email.setCharset(encoding);

        if (logger.isInfoEnabled()) {
            logger.info("systemEmailSender:" + systemEmailSender);
            logger.info("to:" + to);
            logger.info("from:" + from);
            logger.info("mailServer:" + mailServer);
            logger.info("mailPort:" + mailPort);
            logger.info("cc:" + cc);
            logger.info("bcc:" + bcc);
            logger.info("replyTo:" + replyTo);
            logger.info("subject:" + subject);
        }

        if (to.indexOf(";") > -1) {
            cc = to;
            to = from;
        }

        String limitString = CmsPropertyHandler.getEmailRecipientLimit();
        if (limitString != null && !limitString.equals("-1")) {
            try {
                Integer limit = new Integer(limitString);
                int count = 0;
                if (cc != null)
                    count = count + cc.split(";").length;
                if (bcc != null)
                    count = count + bcc.split(";").length;

                logger.info("limit: " + limit + ", count: " + count);
                if (count > limit)
                    throw new Exception("You are not allowed to send mail to more than " + limit
                            + " recipients at a time. This is specified in app settings.");
            } catch (NumberFormatException e) {
                logger.error("Exception validating number of recipients in mailservice:" + e.getMessage(), e);
            }
        }

        email.addTo(to, to);
        email.setFrom(from, from);
        if (cc != null)
            email.setCc(createInternetAddressesList(cc));
        if (bcc != null)
            email.setBcc(createInternetAddressesList(bcc));
        if (replyTo != null)
            email.setReplyTo(createInternetAddressesList(replyTo));

        email.setSubject(subject);

        email.setHtmlMsg(content);

        email.setTextMsg("Your email client does not support HTML messages");

        email.send();

        logger.info("Email sent!");
    } catch (Exception e) {
        logger.error("An error occurred when we tried to send this mail:" + e.getMessage(), e);
        throw new SystemException("An error occurred when we tried to send this mail:" + e.getMessage(), e);
    }
}

From source file:org.ms123.common.workflow.tasks.TaskMailExecutor.java

protected HtmlEmail createHtmlEmail(DelegateExecution execution, String text, String html,
        String attachmentPath) {//from  w w  w  .jav  a 2 s  .  c  o  m
    HtmlEmail email = new HtmlEmail();
    try {
        if (html != null) {
            email.setHtmlMsg(html);
        }
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        if (attachmentPath != null) {
            email.attach(
                    createAttachment(new File(getProcessDocBasedir(execution), attachmentPath).toString()));
        }
        return email;
    } catch (EmailException e) {
        throw new RuntimeException("TaskMailExecutor:Could not create HTML email", e);
    }
}

From source file:org.ms123.common.workflow.TaskSendExecutor.java

protected HtmlEmail createHtmlEmail(DelegateExecution execution, String text, String html,
        String attachmentPath) {// w  ww.j  av  a2s  .c  om
    HtmlEmail email = new HtmlEmail();
    try {
        if (html != null) {
            email.setHtmlMsg(html);
        }
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        if (attachmentPath != null) {
            email.attach(
                    createAttachment(new File(getProcessDocBasedir(execution), attachmentPath).toString()));
        }
        return email;
    } catch (EmailException e) {
        throw new RuntimeException("TaskSendExecutor:Could not create HTML email", e);
    }
}