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

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

Introduction

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

Prototype

HtmlEmail

Source Link

Usage

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 {/* ww  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.jaide.courier.email.MessageHandlerEMail.java

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*//from  w  w w .j  a v  a 2 s . co  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:mailbox.EmailHandler.java

private static void reply(IMAPMessage origin, String username, String emailAddress, String msg) {
    final HtmlEmail email = new HtmlEmail();

    try {/* w  w w . j  a  v a 2  s. com*/
        email.setFrom(Config.getEmailFromSmtp(), Config.getSiteName());
        email.addTo(emailAddress, username);
        String subject;
        if (!origin.getSubject().toLowerCase().startsWith("re:")) {
            subject = "Re: " + origin.getSubject();
        } else {
            subject = origin.getSubject();
        }
        email.setSubject(subject);
        email.setTextMsg(msg);
        email.setCharset("utf-8");
        email.setSentDate(new Date());
        email.addHeader("In-Reply-To", origin.getMessageID());
        email.addHeader("References", origin.getMessageID());
        Mailer.send(email);
        String escapedTitle = email.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, email.getToAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send an email: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

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

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {//from w  w  w.j a v a 2  s . c o m

        // 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:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java

private void sendMailToPerceptiveOpsTeam(EmployeeBO employeeBO) throws Exception {
    try {/*from w ww.jav a2 s.com*/
        //Send the mail
        HtmlEmail emailToSend = new HtmlEmail();
        emailToSend.setHostName(email.getHostName());
        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 employee has joined Perceptive Kolkata.</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  following  actions.</p>\n" + "<ul>\n" + "  <li>Access to Rally.</li>\n"
                + "  <li>Access to Salesforce.</li>\n" + "  <li>Access to Confluence.</li>\n"
                + "  <li>Access to Perceptive AD.</li>\n" + "  <li>Access to TFS.</li>\n" + "</ul>\n"
                + "<p>Thanks,</p>\n" + "<blockquote>\n"
                + "  <p>Perceptive Kolkata Central( http://10.195.17.14/PerceptiveKolkataCentral )</p>\n"
                + "</blockquote>\n" + "</body>\n" + "</html>";
        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();
        emailToSend.addTo("per.special.rad.operations@perceptivesoftware.com", "RAD - Operations");
        emailToSend.addTo("radops@perceptivesoftware.com", "RAD - Operations Team");
        Collection<EmployeeBO> allEmployeesNeedToGetMail = getAllEmployeesKeyedByGroupId()
                .get(Integer.valueOf("14"));
        for (EmployeeBO item : allEmployeesNeedToGetMail) {
            emailToSend.addCc(item.getEmail(), item.getEmployeeName());
        }
        //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central");
        emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata");
        emailToSend.setSubject(
                String.format("New employee joined @ Lexmark Kolkata : %s", employeeBO.getEmployeeName()));
        emailToSend.send();
    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }
}

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

/**
 * DOCUMENT ME!/*from w  ww  . j  ava  2s .c o m*/
 *
 * @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:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * /*from   ww w. j a  v  a 2 s .c o  m*/
 * Envoi l'email.
 * 
 * @throws EmailException
 *             Erreur lors de l'envoi de l'email.
 */
public void send() throws EmailException {

    if (hostProperty == null) {
        log.error("Session email non initialise : envoi des emails impossible.");
        return;
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(hostProperty);

    // To
    if (to != null) {
        for (String adresse : to) {
            email.addTo(adresse);
        }
    }

    // Cc
    if (cc != null) {
        for (String adresse : cc) {
            email.addCc(adresse);
        }
    }

    // Cci
    if (cci != null) {
        for (String adresse : cci) {
            email.addBcc(adresse);
        }
    }

    // Subject
    email.setSubject(subjectPrefix != null ? subjectPrefix + subject : subject);

    // From
    email.setFrom(StringUtils.isNotEmpty(from) ? from : defaultFrom);

    // Message & Html
    if (message != null) {
        email.setTextMsg(message);
    }
    if (html != null) {
        email.setHtmlMsg(html);
    }

    if (StringUtils.isNotEmpty(this.charset)) {
        email.setCharset(this.charset);
    }

    email.buildMimeMessage();

    // Attachments
    for (AttachmentBean attachement : attachments) {
        email.attach(attachement.getDataSource(), attachement.getName(), attachement.getDescription());
    }

    email.sendMimeMessage();

}

From source file:bean.OrdemBean.java

private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) {
    try {/*from  www  .j a va2 s.c o  m*/
        String emailAutenticacao = "chravent@gmail.com";
        String senhaAutenticacao = "23421Felix";

        //MultiPartEmail email = new MultiPartEmail();
        HtmlEmail emailOrdem = new HtmlEmail();
        //Informaes do Servidor
        emailOrdem.setHostName("smtp.gmail.com");
        emailOrdem.setSmtpPort(587);
        //DADOS DE QUEM ESTA ENVIANDO O E-MAIL
        emailOrdem.setFrom(emailAutenticacao, "GESPED");
        //PARA QUEM VAI O EMAIL, VC PODE COLOCAR O USUARIO DE CRIACAO,  O QUE ACOMPANHA E O ALTERACO
        if (!novaOrdem) {
            if (ordemNova.getUsuUsuarioByUsuAcompanha() != null) {
                emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuAcompanha().getUsuEmail(),
                        ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario());
                emailOrdem.setSubject("Atribuio de Ordem - Com Acompanhamento");
            } else {
                emailOrdem.addTo(ordemNova.getDepDepartamentoByDepIdDestino().getDepEmail(),
                        ordemNova.getUsuUsuarioByUsuCriacao().getUsuUsuario());
                emailOrdem.setSubject("Atribuio de Ordem - Sem Acompanhamento");
            }
        } else {
            emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuCriacao().getUsuEmail(),
                    ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario());
            emailOrdem.setSubject("Criao de Nova de Ordem");
        }

        emailOrdem.setSocketConnectionTimeout(30000);
        emailOrdem.setSocketTimeout(30000);
        //if (contaPadrao.contains("gmail")) {
        emailOrdem.setSSL(true);
        emailOrdem.setTLS(true);

        //Autenticando no servidor
        emailOrdem.setAuthentication(emailAutenticacao, senhaAutenticacao);
        //Montando o e-mail
        StringBuilder htmlEmail = new StringBuilder();
        htmlEmail.append(
                "<html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\" /> </head><body>");
        htmlEmail.append("<br/>").append("Ol ").append(ordem.getUsuUsuarioByUsuAcompanha().getUsuDescricao())
                .append(",").append("<br/>");
        htmlEmail.append("Uma Ordem Atribuda para seu Usurio:").append("<br/>");
        htmlEmail.append("Protocolo : ").append(ordem.getOrdNumProtocolo()).append("<br/>");
        if (ordem.getOrdPrioridade()) {
            htmlEmail.append("Prioridade : Urgente").append("<br/>");
        } else {
            htmlEmail.append("Prioridade : Normal").append("<br/>");
        }

        htmlEmail.append("\"</body></html>\"");

        //PODE ENVIAR UMA COPIA OCULPA
        emailOrdem.setHtmlMsg(htmlEmail.toString());
        //            List<InternetAddress> copiasOcultas = new ArrayList<>();
        //            copiasOcultas.add(new InternetAddress("enio.a.nunes@gmail.com"));
        //            emailOrdem.setBcc(copiasOcultas);
        emailOrdem.send();

        // context.addMessage(null, new FacesMessage("E-mail enviado com sucesso", this.destino));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:controllers.ProjectApp.java

private static void sendTransferRequestMail(ProjectTransfer pt) {
    HtmlEmail email = new HtmlEmail();
    try {/*from w w  w .  j a v  a2  s.com*/
        String acceptUrl = pt.getAcceptUrl();
        String message = Messages.get("transfer.message.hello", pt.destination) + "\n\n"
                + Messages.get("transfer.message.detail", pt.project.name, pt.newProjectName, pt.project.owner,
                        pt.destination)
                + "\n" + Messages.get("transfer.message.link") + "\n\n" + acceptUrl + "\n\n"
                + Messages.get("transfer.message.deadline") + "\n\n" + Messages.get("transfer.message.thank");

        email.setFrom(Config.getEmailFromSmtp(), pt.sender.name);
        email.addTo(Config.getEmailFromSmtp(), "Yobi");

        User to = User.findByLoginId(pt.destination);
        if (!to.isAnonymous()) {
            email.addBcc(to.email, to.name);
        }

        Organization org = Organization.findByName(pt.destination);
        if (org != null) {
            List<OrganizationUser> admins = OrganizationUser.findAdminsOf(org);
            for (OrganizationUser admin : admins) {
                email.addBcc(admin.user.email, admin.user.name);
            }
        }

        email.setSubject(
                String.format("[%s] @%s wants to transfer project", pt.project.name, pt.sender.loginId));
        email.setHtmlMsg(Markdown.render(message));
        email.setTextMsg(message);
        email.setCharset("utf-8");
        email.addHeader("References", "<" + acceptUrl + "@" + Config.getHostname() + ">");
        email.setSentDate(pt.requested);
        Mailer.send(email);
        String escapedTitle = email.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//from w w w  .  ja  v a 2 s  . c o  m
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

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