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

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

Introduction

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

Prototype

public List<InternetAddress> getToAddresses() 

Source Link

Document

Get the list of "To" addresses.

Usage

From source file:com.github.robozonky.notifications.EmailHandler.java

@Override
public void send(final SessionInfo sessionInfo, final String subject, final String message,
        final String fallbackMessage) throws Exception {
    final HtmlEmail email = createNewEmail(sessionInfo);
    email.setSubject(subject);/* w w w .  ja v a2  s. co m*/
    email.setHtmlMsg(message);
    email.setTextMsg(fallbackMessage);
    LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
            email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
            getSmtpUsername());
    email.send();
}

From source file:io.marto.aem.utils.email.FreemarkerTemplatedMailerTest.java

@Test
public void testGatewayFormatsAndSendsMessage() throws EmailException, IOException, MessagingException {
    Map<String, Object> model = createModel();

    String recipients[] = new String[] { "joe@me.com", "jack@test.com" };
    String subject = "Test Email";
    String sender = "admin@marto.io";
    String template = "/templates/helloworld.ftl";

    mailer.sendEmail(recipients, sender, subject, template, model);
    mailer.clear();/*from  w  w  w.j  a v a  2 s.  co  m*/

    HtmlEmail htmlMail = sentEmail.get();

    assertEquals(subject, htmlMail.getSubject());
    assertEquals(sender, htmlMail.getFromAddress().getAddress());
    assertEquals(recipients.length, htmlMail.getToAddresses().size());
    assertEquals(recipients[0], ((InternetAddress) htmlMail.getToAddresses().get(0)).getAddress());
    assertEquals(recipients[1], ((InternetAddress) htmlMail.getToAddresses().get(1)).getAddress());

    String msg = getEmail(htmlMail);

    assertThat(msg, containsString("FreeMarker Template example: Hello World!"));
    assertThat(msg, containsString("1. India"));
    assertThat(msg, containsString("2. United States"));
    assertThat(msg, containsString("3. Germany"));
    assertThat(msg, containsString("4. France"));

    assertThat(msg, containsString("To: \"joe@me.com\" <joe@me.com>, \"jack@test.com\" <jack@test.com>"));
    assertThat(msg, containsString("From: \"admin@marto.io\" <admin@marto.io>"));
    assertThat(msg, containsString("Subject: Test Email"));
}

From source file:mailbox.EmailHandler.java

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

    try {//from www  .  j  a v  a 2  s. c  om
        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:actors.ValidationEmailSender.java

@Override
public void onReceive(Object object) {
    if (!(object instanceof Email)) {
        return;//from   w  ww. jav  a  2 s . c  om
    }

    Email email = (Email) object;

    final HtmlEmail htmlEmail = new HtmlEmail();

    try {
        htmlEmail.setFrom(Config.getEmailFromSmtp(), utils.Config.getSiteName());
        htmlEmail.addTo(email.email, email.user.name);
        htmlEmail.setSubject(Messages.get("emails.validation.email.title", utils.Config.getSiteName()));
        htmlEmail.setHtmlMsg(getMessage(email.confirmUrl));
        htmlEmail.setCharset("utf-8");
        Mailer.send(htmlEmail);
        String escapedTitle = htmlEmail.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, htmlEmail.getToAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

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");
    }/*ww  w.j a v a2 s  .com*/

    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: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   ww w  .j  av  a 2 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:dk.dma.ais.abnormal.analyzer.reports.ReportMailer.java

/**
 * Send email with subject and message body.
 * @param subject the email subject./*from w ww  .  j av  a  2 s .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.perceptive.epm.perkolcentral.bl.EmployeeBL.java

private void sendMailToPerceptiveOpsTeam(EmployeeBO employeeBO) throws Exception {
    try {/*from  ww w .j a v a 2 s. co  m*/
        //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);
    }
}