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:br.com.atmatech.sac.controller.Email.java

public void emaiMassa(String smtp, String user, String password, Integer porta, Boolean ssl, Boolean tls,
        List<PessoaBeans> emailto, String emailfrom, String conteudo, String assunto)
        throws EmailException, MalformedURLException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtp); // o servidor SMTP para envio do e-mail
    Integer indice2 = 0;/*  w w w.  ja  va2 s  . com*/
    Integer j = 0;
    for (int i = 0; (i < emailto.size()) && (i < 45); i++) {
        email.addTo(emailto.get(i).getEmail());//destinatario            
        indice2 = i;
    }
    while (j <= indice2) {
        emailto.remove(0);
        j++;
    }
    conteudo = conteudo.replaceAll("\n", "<p>");
    email.setFrom(emailfrom); // remetente        
    //email.addCc(emailfrom);
    email.setSubject(assunto);
    // configura a mensagem para o formato HTML        
    email.setHtmlMsg("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"
            + conteudo + "</html>");
    email.setAuthentication(user, password);
    email.setSmtpPort(porta);
    email.setSSL(ssl);
    email.setTLS(tls);
    email.send();
    if (emailto != null) {
        if (emailto.size() > 1) {
            emaiMassa(smtp, user, password, porta, ssl, tls, emailto, emailfrom, conteudo, assunto);
        }
    }

}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * smtp??/*from  w  ww  .  java  2 s .c  o m*/
 * 
 * @param subject subject
 * @param htmlBody htmlBody
 * @param properties properties
 * @param from from
 * @param toList toList
 * @param ccList ccList
 * @param bccList bccList
 * @param embedUrls 
 * @throws EmailException EmailException
 */
@SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseStringBufferForStringAppends" })
public static void sendMail(String subject, String htmlBody, Map<String, String> properties, String from,
        List<String> toList, List<String> ccList, List<String> bccList, Map<String, URL> embedUrls)
        throws EmailException {
    HtmlEmail htmlEmail = getEmail();
    // from?
    if (!Strings.isNullOrEmpty(from)) {
        Address fromMailbox = parseMailbox(from);
        if (fromMailbox != null && StringUtils.isNotBlank(from)) {
            htmlEmail.setFrom(fromMailbox.getAddress(), fromMailbox.getName());
        }
    }
    // to?
    if (toList != null && !toList.isEmpty()) {
        for (String to : toList) {
            if (StringUtils.isNotBlank(to)) {
                Address toMailbox = parseMailbox(to);
                htmlEmail.addTo(toMailbox.getAddress(), toMailbox.getName());
            }
        }
    }
    // cc?
    if (ccList != null && !ccList.isEmpty()) {
        for (String cc : ccList) {
            if (StringUtils.isNotBlank(cc)) {
                Address ccMailbox = parseMailbox(cc);
                htmlEmail.addCc(ccMailbox.getAddress(), ccMailbox.getName());
            }
        }
    }
    // bcc?
    if (bccList != null && !bccList.isEmpty()) {
        for (String bcc : bccList) {
            if (StringUtils.isNotBlank(bcc)) {
                Address bccMailbox = parseMailbox(bcc);
                htmlEmail.addBcc(bccMailbox.getAddress(), bccMailbox.getName());
            }
        }
    }
    // 
    htmlEmail.setSubject(subject);
    htmlEmail.setHtmlMsg(htmlBody);
    htmlEmail.setSentDate(new Date());
    // 
    if (properties != null) {
        htmlEmail.setHeaders(properties);
    }
    // 
    if (embedUrls != null && !embedUrls.isEmpty()) {
        for (Map.Entry<String, URL> entry : embedUrls.entrySet()) {
            String cid = entry.getKey();
            URL url = entry.getValue();
            String fileName = StringUtils.substringAfterLast(url.getPath(), "/");
            if (StringUtils.isBlank(fileName)) {
                fileName = cid;
            } else {
                fileName += IdUtils.genStringId();
            }
            htmlEmail.embed(new URLDataSource(url), fileName, cid);
        }
    }
    htmlEmail.send();
}

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

public void emailGiroTolak(Giro gironya, String namaCustomer, String customerID) {

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

    String msg = "<html>" + "<head>"
            + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
            + "<title>Untitled Document</title>" + "<style type=\"text/css\">" + "p {"
            + "font-family: \"Courier New\", Courier, monospace;" + "font-size: 12px;" + "}" + "</style>"
            + "</head>" + "<p>Yth, </p>"
            + "<p>Berikut kami informasikan customer/outlet baru ditambahkan dalam daftar giro tolak;</p> "
            + "<br/>" + "<p><pre>" + "Customer ID      : " + customerID + "<br/>" + "Nama Customer    : "
            + namaCustomer + "<br/>" + "Nomor Giro       : " + gironya.getNomorGiro() + "<br/>"
            + "Nilai            : " + Rupiah.format(gironya.getNilai()) + "<br/>" + "Bank             : "
            + gironya.getBank() + "<br/>" + "Keterangan       : " + gironya.getKeterangan() + "" + "<pre>"
            + "</p>" + "<br/>" + "<br/>" + "<br/>"
            + "<p>Outlet akan di hold sementara oleh bagian Data Proses, selama di hold outlet tidak bisa melakukan order</p>"
            + "<br/>" + "<br/>" + "<p><i>Note : " + "<br>" + "Info giro " + url + "<br/>"
            + "Ini adalah email otomatis, mohon tidak membalas email ini !</i></p>" + "</html>";

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

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

}

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;/*from w ww.j av a2s .c  o m*/
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

From source file:dk.dma.ais.abnormal.analyzer.reports.ReportMailer.java

/**
 * Send email with subject and message body.
 * @param subject the email subject.// w ww  .java 2s.  c o m
 * @param body the email body.
 */
public void send(String subject, String body) {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_HOST, "localhost"));
        email.setSmtpPort(configuration.getInt(CONFKEY_REPORTS_MAILER_SMTP_PORT, 465));
        email.setAuthenticator(
                new DefaultAuthenticator(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_USER, "anonymous"),
                        configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_PASS, "guest")));
        email.setStartTLSEnabled(false);
        email.setSSLOnConnect(configuration.getBoolean(CONFKEY_REPORTS_MAILER_SMTP_SSL, true));
        email.setFrom(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_FROM, ""));
        email.setSubject(subject);
        email.setHtmlMsg(body);
        String[] receivers = configuration.getStringArray(CONFKEY_REPORTS_MAILER_SMTP_TO);
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        email.send();
        LOG.info("Report sent with email to " + email.getToAddresses().toString() + " (\"" + subject + "\")");
    } catch (EmailException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*from  w w w . ja v a 2 s.  com*/
 *
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void sendIdentity(Session session, String repositoryName, String from, String to, String subject,
        String body) throws MailException {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(session);
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setHtmlMsg(body);
        email.setCharset(Charset.defaultCharset().displayName());

        email.send();
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
    }
}

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

public void emailTolakUpdate(Giro gironya) {

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

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

    try {/* ww  w  .  j  ava2  s .c om*/
        HtmlEmail mail = new HtmlEmail();
        mail.setHostName(Util.setting("smtp_host"));
        mail.setSmtpPort(Integer.parseInt(Util.setting("smtp_port")));
        mail.setAuthenticator((Authenticator) new DefaultAuthenticator(Util.setting("smtp_username"),
                Util.setting("smtp_password")));
        mail.setFrom(Util.setting("email_from"));
        for (String s : Util.setting("email_to").split(",")) {
            mail.addTo(s.trim());
        }

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

}

From source file:de.cosmocode.palava.services.mail.EmailFactory.java

@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */

    final Element root = document.getRootElement();

    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");

    final List<Element> attachments = root.getChildren("attachment");

    final Map<ContentType, String> available = new HashMap<ContentType, String>();

    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }/*from w  w  w.  j  av a2 s .co m*/
        available.put(messageType, element.getText());
    }

    final Email email;

    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);

        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }

        /**
         * Add html message
         */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }

        /**
         * Add plain text alternative
         */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }

        /**
         * Embedded binary data
         */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);

            final File file;

            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }

            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        /**
         * Attached binary data
         */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");

            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);

            if (!file.exists())
                file = new File(embed.getResourcePath(), path);

            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }

    final String subject = root.getChildText("subject");
    email.setSubject(subject);

    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);

    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }

    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }

    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }

    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }

    return email;
}

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 {/*w  w  w  .j a  v  a2 s. 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.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java

public void send() throws EmailException {

    if (files != null && urls != null) {
        attachments = new EmailAttachment[files.length + urls.length];

        int cnt = 0;

        for (int i = 0; i < files.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setPath(files[i].getPath());
            attachments[cnt].setName(files[i].getName());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);

            cnt++;//from  www .  j av  a  2 s. co m
        }

        for (int i = 0; i < urls.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setURL(urls[i]);
            attachments[cnt].setName(urls[i].getFile());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);
            cnt++;
        }

    } else if (files != null) {
        attachments = new EmailAttachment[files.length];

        for (int i = 0; i < files.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setPath(files[i].getPath());
            attachments[i].setName(files[i].getName());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    } else if (urls != null) {
        attachments = new EmailAttachment[urls.length];

        for (int i = 0; i < urls.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setURL(urls[i]);
            attachments[i].setName(urls[i].getFile());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(Config.get("mailHost", ""));
    email.setSmtpPort(Config.getConfigInt("mailPort", 25));

    email.setTLS(Config.getConfigBoolean("mailTLS", false));
    email.setSSL(Config.getConfigBoolean("mailSSL", false));

    //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25));
    email.setAuthenticator(
            new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", "")));

    email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null));

    email.setSubject(subject);
    email.setHtmlMsg(body);
    email.setTextMsg(nohtmlmsg);

    for (int i = 0; i < adress.length; i++) {
        email.addTo(adress[i]);
    }

    if (cc != null) {
        for (int i = 0; i < cc.length; i++) {
            email.addCc(cc[i]);
        }
    }

    if (attachments != null) {
        for (int i = 0; i < attachments.length; i++) {
            email.attach(attachments[i]);
        }
    }

    email.send();

}