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

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

Introduction

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

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

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

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {//from   w ww .jav  a  2s. 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:br.ufg.reqweb.components.MailBean.java

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

From source file:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java

@TriggersRemove(cacheName = { "EmployeeCache", "GroupCache",
        "EmployeeKeyedByGroupCache" }, when = When.AFTER_METHOD_INVOCATION, removeAll = true, keyGenerator = @KeyGenerator(name = "HashCodeCacheKeyGenerator", properties = @Property(name = "includeMethod", value = "false")))
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, rollbackFor = ExceptionWrapper.class)
public void updateAllEmployee(List<EmployeeBO> employeeListFromLDAP) throws ExceptionWrapper {
    try {//from  w w  w.j  av  a  2s  . c o m
        String messageTemplateAdded = "<html>\n" + "<head>\n" + "</head>\n" + "\n"
                + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n"
                + "  <p>A new user is added to the system.</p>\n" + "</blockquote>\n" + "<ul>\n"
                + "  <li><strong><em>User Name</em></strong>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>User Short Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>Employee Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><strong><em>User Email-Id</em></strong>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Mobile Number</strong></em>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Job Title</strong></em> : <strong>%s</strong></li>\n" + "</ul>\n"
                + "<p>Please take necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n"
                + "  <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>";

        String messageTemplateDeleted = "<html>\n" + "<head>\n" + "</head>\n" + "\n"
                + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n"
                + "  <p>An  user is removed from the system.</p>\n" + "</blockquote>\n" + "<ul>\n"
                + "  <li><strong><em>User Name</em></strong>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>User Short Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>Employee Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><strong><em>User Email-Id</em></strong>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Mobile Number</strong></em>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Job Title</strong></em> : <strong>%s</strong></li>\n" + "</ul>\n"
                + "<p>Please take necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n"
                + "  <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>";

        LinkedHashMap<Long, EmployeeBO> employeeLinkedHashMap = employeeDataAccessor.getAllEmployees();
        for (EmployeeBO employeeBO : employeeListFromLDAP) {
            if (!employeeLinkedHashMap.containsKey(Long.valueOf(employeeBO.getEmployeeId()))) {
                //Add a new employee
                Employee employee = new Employee();
                employee.setEmployeeId(Long.parseLong(employeeBO.getEmployeeId()));
                employee.setEmail(employeeBO.getEmail());
                employee.setEmployeeName(employeeBO.getEmployeeName());
                employee.setEmployeeUid(employeeBO.getEmployeeUid());
                employee.setJobTitle(employeeBO.getJobTitle());
                employee.setMobileNumber(employeeBO.getMobileNumber());
                employee.setManager(employeeBO.getManager());
                employee.setManagerEmail(employeeBO.getManagerEmail());
                employee.setExtensionNum(employeeBO.getExtensionNum());
                employee.setWorkspace(employeeBO.getWorkspace());
                employee.setIsActive(true);
                employeeDataAccessor.addEmployee(employee);
                LoggingHelpUtil.printDebug(String.format("Adding user ----> %s with details %s %s",
                        employeeBO.getEmployeeName(), System.getProperty("line.separator"),
                        ReflectionToStringBuilder.toString(employeeBO)));
                //Send the mail
                HtmlEmail emailToSend = new HtmlEmail();
                emailToSend.setHostName(email.getHostName());
                String messageToSend = String.format(messageTemplateAdded, employeeBO.getEmployeeName(),
                        employeeBO.getEmployeeUid(), employeeBO.getEmployeeId().toString(),
                        employeeBO.getEmail(), employeeBO.getMobileNumber(), employeeBO.getJobTitle());

                emailToSend.setHtmlMsg(messageToSend);
                //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend));
                emailToSend.getToAddresses().clear();
                //Send mail to scrum masters and Development Managers Group Id 15
                Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union(
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")),
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15")));
                for (EmployeeBO item : allEmployeesNeedToGetMail) {
                    emailToSend.addTo(item.getEmail(), item.getEmployeeName());
                }
                emailToSend.addTo(employeeBO.getManagerEmail(), employeeBO.getManager());//Send the mail to manager
                //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central");
                emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata");
                emailToSend.setSubject(String.format("New employee added : %s", employeeBO.getEmployeeName()));
                emailToSend.send();
                //==========================Mail send ends here===========================================================================================================
                //sendMailToPerceptiveOpsTeam(employeeBO);//Send mail to operations team in Shawnee
            } else {
                //Update a new employee
                employeeDataAccessor.updateEmployee(employeeBO);
                LoggingHelpUtil.printDebug(String.format("Updating user ----> %s with details %s %s",
                        employeeBO.getEmployeeName(), System.getProperty("line.separator"),
                        ReflectionToStringBuilder.toString(employeeBO)));
            }

            //========================================================================================================================================
        }
        //Delete employees if any
        for (Object obj : employeeLinkedHashMap.values()) {
            final EmployeeBO emp = (EmployeeBO) obj;
            if (!CollectionUtils.exists(employeeListFromLDAP, new Predicate() {
                @Override
                public boolean evaluate(Object o) {
                    return emp.getEmployeeId().trim().equalsIgnoreCase(((EmployeeBO) o).getEmployeeId().trim()); //To change body of implemented methods use File | Settings | File Templates.
                }
            })) {
                emp.setActive(false); //Soft delete the Employee
                employeeDataAccessor.updateEmployee(emp);//Rest deletion will be taken care by the Trigger AFTER_EMPLOYEE_UPDATE
                LoggingHelpUtil.printDebug(
                        String.format("Deleting user ----> %s with details %s %s", emp.getEmployeeName(),
                                System.getProperty("line.separator"), ReflectionToStringBuilder.toString(emp)));
                //Send the mail
                HtmlEmail emailToSend = new HtmlEmail();
                emailToSend.setHostName(email.getHostName());

                String messageToSend = String.format(messageTemplateDeleted, emp.getEmployeeName(),
                        emp.getEmployeeUid(), emp.getEmployeeId().toString(), emp.getEmail(),
                        emp.getMobileNumber(), emp.getJobTitle());
                emailToSend.setHtmlMsg(messageToSend);
                //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend));
                emailToSend.getToAddresses().clear();
                //Send mail to scrum masters ==Group ID 14 and Development Managers Group Id 15
                Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union(
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")),
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15")));
                for (EmployeeBO item : allEmployeesNeedToGetMail) {
                    emailToSend.addTo(item.getEmail(), item.getEmployeeName());
                }
                //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central");
                emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata");
                emailToSend.setSubject(String.format("Employee removed : %s", emp.getEmployeeName()));
                emailToSend.send();
            }
        }

        luceneUtil.indexUserInfo(getAllEmployees().values());

    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }
}

From source file:de.hybris.platform.lichextendtrail.emailservice.DefaultLichEmailService.java

@Override
public boolean send(EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }/*from   ww  w  . j a  v a  2s . co  m*/

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            setAddresses(message, email, toAddresses);

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));
            addReplyTo(message, email);
            email.setSubject(message.getSubject());
            //???
            if (message.getSubject().equals("?Customer Registration\n")) {
                email.setSubject("?");
                //??
                String emailToAddress = email.getToAddresses().get(0).toString();
                emailToAddress = emailToAddress.substring(emailToAddress.indexOf('<') + 1,
                        emailToAddress.indexOf('>'));
                //
                email.setHtmlMsg(LichValue.getEmailContent(emailToAddress));
            }
            //??? 
            else {
                email.setHtmlMsg(getBody(message));
            }
            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (!processAttachmentsSuccessful(email, attachments)) {
                return false;
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            logInfo(message, e);
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}

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

/**
*
* @param destinatario// w w  w . j  a  va2 s .  co m
* @param nome
* @param assunto
* @throws IOException
*/

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

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

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

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

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

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

}

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

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {//www .j a v a 2 s.  com

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

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

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

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

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

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

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

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

}

From source file: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 . ja va  2s.  c  om

        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:br.com.itfox.utils.SendHtmlFormatedEmail.java

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

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

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

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

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

}

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

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*/*from   w  w w.  ja  v  a2s .c o m*/
     * Check if the obligatory parameters are there.
     */
    for (String key : obligatoryMappingParameters)
        if (!parameters.containsKey(key))
            throw new CourierException(new MissingParameterException(
                    "The parameter '" + key + "' was expected but couldn't be found."));

    /*
     * Now retrieve the obligatory parameters.
     */
    String configurationName = (String) parameters.get(MAPPING_PARAM_CONFIGURATION_NAME);
    String templatePath = (String) parameters.get(MAPPING_PARAM_TEMPLATE_PATH);
    if ((templatePath != null) && (!templatePath.endsWith("/")))
        templatePath += "/";
    else if (templatePath == null)
        templatePath = "/";

    Class<?> templatePathClass = (Class<?>) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_CLASS);
    File templatePathFile = (File) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_FILE);

    String templateName = (String) parameters.get(MAPPING_PARAM_TEMPLATE_NAME);
    TemplateTypeEnum templateTypeEnum = (TemplateTypeEnum) parameters.get(MAPPING_PARAM_TEMPLATE_TYPE);
    String recipientFirstname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_FIRSTNAME);
    String recipientLastname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_LASTNAME);
    String recipientEMail = (String) parameters.get(MAPPING_PARAM_RECIPIENT_EMAIL);
    String ccRecipientFirstname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_FIRSTNAME);
    String ccRecipientLastname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_LASTNAME);
    String ccRecipientEMail = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_EMAIL);

    /*
     * The next three parameters are optional, as they might also be specified in the SMTP configuration file. If they are specified they
     * tell us to overwrite what was specified in the SMTP configuration file and use those values (firstname, lastname, e-mail) for the
     * sender instead.
     */
    String senderFirstname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_FIRSTNAME))
        senderFirstname = (String) parameters.get(MAPPING_PARAM_SENDER_FIRSTNAME);

    String senderLastname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_LASTNAME))
        senderLastname = (String) parameters.get(MAPPING_PARAM_SENDER_LASTNAME);

    String senderEMail = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_EMAIL))
        senderEMail = (String) parameters.get(MAPPING_PARAM_SENDER_EMAIL);

    /*
     * Will be used for parsing the templates.
     */
    StringWriter writer = new StringWriter();

    try {
        /*
         * Construct the template that we're about to process. First set the path to load the template(s) from. In case a Directory was given
         * as the base for template loading purposes use that instead.
         */
        if (templatePathFile == null) {
            if (templatePathClass == null)
                templatingConfiguration.setClassForTemplateLoading(getClass(), templatePath);
            else
                templatingConfiguration.setClassForTemplateLoading(templatePathClass, templatePath);
        } else
            templatingConfiguration.setDirectoryForTemplateLoading(templatePathFile);

        /*
         * Get the headers and Freemarker-parse them. If there are no headers then ignore the errors. The file has to be one header per line,
         * header name and value separated by a colon (":").
         */
        Template template;

        Map<String, String> headers = new HashMap<String, String>();
        String headersFilename = retrieveTemplateFilename(templateName,
                MessageHandlerEMail.TEMPLATENAME_SUFFIX_HEADERS, true);
        if (headersFilename != null) {
            try {
                template = loadTemplate(headersFilename);
                template.process(parameters, writer);
                BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
                headers = new HashMap<String, String>();
                String str = "";
                while ((str = reader.readLine()) != null) {
                    String[] split = str.split(":");
                    if (split.length > 1)
                        headers.put(split[0].trim(), split[1].trim());
                }
            } catch (IOException ioe) {
                // The header file is optional, hence we don't care if it couldn't be found
            }
        }

        /*
         * Get the subject line and Freemarker-parse it.
         */
        String subject = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_SUBJECT,
                templateName, false);

        /*
         * Get the body content and Freemarker-parse it.
         */
        String contentText = null;
        String contentHtml = null;

        /*
         * Load all requested versions of the template.
         */
        if (templateTypeEnum == TemplateTypeEnum.TEXT) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
        } else if (templateTypeEnum == TemplateTypeEnum.HTML) {
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.BOTH) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.ANY) {
            try {
                contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                        templateName, false);
            } catch (IOException ioe) {
            } finally {
                try {
                    contentHtml = loadAndProcessTemplate(parameters,
                            MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true);
                } catch (IOException ioe) {
                    throw new RuntimeException(
                            "Neither the HTML nor the TEXT-only version of the e-mail template '" + templateName
                                    + "' could be found. Are you sure they reside in '" + templatePath
                                    + "' as '" + templateName + "_body.ftl.html' or '" + templateName
                                    + "_body.ftl.txt'?",
                            ioe);
                }
            }
        }

        /*
         * Set the parameters that are identical for that sender, for all recipients.
         * Note: attachments may not be removed once they have been attached, hence the performance-improving caching had to be removed.
         */
        SmtpConfiguration smtpConfiguration = (SmtpConfiguration) smtpConfigurations.get(configurationName);
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset("UTF-8");
        htmlEmail.setHostName(smtpConfiguration.getSmtpHostname());
        htmlEmail.setSmtpPort(smtpConfiguration.getSmtpPort());
        if (smtpConfiguration.isTls()) {
            htmlEmail.setAuthenticator(
                    new DefaultAuthenticator(smtpConfiguration.getUsername(), smtpConfiguration.getPassword()));
            htmlEmail.setStartTLSEnabled(smtpConfiguration.isTls());
        }
        htmlEmail.setSSLOnConnect(smtpConfiguration.isSsl());

        /*
         * Changing the sender, to differ from what was specified in the particular SMTP configuration, is optional. As explained above this
         * will only happen if they were specified by the caller.
         */
        if ((senderFirstname != null) || (senderLastname != null) || (senderEMail != null))
            htmlEmail.setFrom(senderEMail, senderFirstname + " " + senderLastname);
        else
            htmlEmail.setFrom(smtpConfiguration.getFromEMail(), smtpConfiguration.getFromSenderName());

        /*
         * Set the parameters that differ for each recipient.
         */
        htmlEmail.addTo(recipientEMail, recipientFirstname + " " + recipientLastname);
        if ((ccRecipientFirstname != null) && (ccRecipientLastname != null) && (ccRecipientEMail != null))
            htmlEmail.addCc(ccRecipientEMail, ccRecipientFirstname + " " + ccRecipientLastname);
        htmlEmail.setHeaders(headers);
        htmlEmail.setSubject(subject);

        /*
         * Set the HTML and Text version of the e-mail body.
         */
        if (contentHtml != null)
            htmlEmail.setHtmlMsg(contentHtml);
        if (contentText != null)
            htmlEmail.setTextMsg(contentText);

        /*
         * Add attachments, if available.
         */
        if (parameters.containsKey(MAPPING_PARAM_ATTACHMENTS)) {
            @SuppressWarnings("unchecked")
            List<EmailAttachment> attachments = (List<EmailAttachment>) parameters
                    .get(MAPPING_PARAM_ATTACHMENTS);
            for (EmailAttachment attachment : attachments) {
                htmlEmail.attach(attachment);
            }
        }

        /*
         * Finished - now send the e-mail.
         */
        htmlEmail.send();
    } catch (IOException ioe) {
        throw new CourierException(ioe);
    } catch (TemplateException te) {
        throw new CourierException(te);
    } catch (EmailException ee) {
        throw new CourierException(ee);
    } finally {
        if (writer != null) {
            writer.flush();

            try {
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

From source file:com.aquest.emailmarketing.web.service.SendEmail.java

/**
 * Send email.//from   www .ja  v a2  s . c o 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());
}