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

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

Introduction

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

Prototype

public List<InternetAddress> getToAddresses() 

Source Link

Document

Get the list of "To" addresses.

Usage

From source file:com.github.triceo.robozonky.notifications.email.AbstractEmailingListener.java

@Override
public void handle(final T event) {
    if (!this.shouldSendEmail(event)) {
        LOGGER.debug("Will not send e-mail.");
        return;/*from   www  . ja v  a  2  s . co m*/
    } else
        try {
            final Email email = AbstractEmailingListener.createNewEmail(properties);
            email.setSubject(this.getSubject(event));
            email.setMsg(TemplateProcessor.INSTANCE.process(this.getTemplateFileName(), this.getData(event)));
            LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
                    email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
                    properties.getSmtpUsername());
            email.send();
            emailsOfThisType.increase();
            this.properties.getGlobalCounter().increase();
        } catch (final Exception ex) {
            throw new RuntimeException("Failed processing event.", ex);
        }

}

From source file:ch.sdi.core.impl.mail.MailCreatorTest.java

@Test
public void testCreateMailFor() throws Throwable {
    PropertiesPerson person = new PropertiesPerson("person", myPersonProps);
    Email email = myClassUnderTest.createMailFor(person);
    myLog.debug("Created Mail: " + email);
    Assert.assertNotNull(email);/*from   ww  w .jav a 2  s.c o m*/
    Assert.assertEquals(THIS_IS_THE_SUBJECT, email.getSubject());
    Object content = Whitebox.getInternalState(email, "content");
    Assert.assertNotNull(content);
    Assert.assertEquals(THIS_IS_THE_BODY, content);
    List<InternetAddress> addresses = email.getToAddresses();
    Assert.assertNotNull(addresses);
    Assert.assertEquals(1, addresses.size());

}

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java

@Test
public void testBuildWithDefaults() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Email email = mailBuilder.build("Stop your messing around, Better think of your future...",
            "rudy@ghosttown", Collections.emptyMap());
    email.buildMimeMessage();/* w  w  w  .j ava2 s  .com*/
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("dandy.livingstone@kingston.jamaica", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilderIT.java

@Test
public void testBuildWithData() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Map<String, String> configuration = new HashMap<>();
    configuration.put("mail.subject", "Rudy, A Message to You");
    configuration.put("mail.from", "specials@thespecials.com");
    final Map data = Collections.singletonMap("mail", configuration);
    final Email email = mailBuilder.build("A Message to You, Rudy", "rudy@ghosttown", data);
    email.buildMimeMessage();/*w ww  . j  ava  2  s  .  c o m*/
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("specials@thespecials.com", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}

From source file:org.sigmah.server.mail.DummyMailSender.java

@Override
public void send(Email email) throws EmailException {
    if (email == null || ArrayUtils.isEmpty(email.getToAddresses())) {
        // does nothing.
        throw new EmailException("Email object null or invalid.");
    }//from   www . j a va  2s. c o m

    Assert.assertNotNull(email.getFromAddress());
    Assert.assertFalse(email.getFromAddress().trim().isEmpty());

    Assert.assertNotNull(email.getSubject());
    Assert.assertFalse(email.getSubject().isEmpty());

    Assert.assertNotNull(email.getContent());
    Assert.assertFalse(email.getContent().isEmpty());

    Assert.assertNotNull(email.getContentType());
    Assert.assertFalse(email.getContentType().isEmpty());

    Assert.assertNotNull(email.getEncoding());
    Assert.assertFalse(email.getEncoding().isEmpty());

    // Building the output
    System.out.println("From: \"" + email.getFromName() + "\" <" + email.getFromAddress() + '>');

    final StringBuilder toAddressesBuilder = new StringBuilder();
    for (final String address : email.getToAddresses()) {
        toAddressesBuilder.append(address).append(", ");
    }
    toAddressesBuilder.setLength(toAddressesBuilder.length() - 2);
    System.out.println("To: " + toAddressesBuilder);

    if (ArrayUtils.isNotEmpty(email.getCcAddresses())) {
        final StringBuilder ccAddressesBuilder = new StringBuilder();
        for (final String address : email.getCcAddresses()) {
            ccAddressesBuilder.append(address).append(", ");
        }
        ccAddressesBuilder.setLength(toAddressesBuilder.length() - 2);
        System.out.println("Cc: " + ccAddressesBuilder);
    }

    System.out.println("Subject: " + email.getSubject());
    final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
    System.out.println("Date: " + dateFormat.format(new Date()));
    System.out.println("Content-Type: " + email.getContentType() + ";charset=" + email.getEncoding());

    System.out.println();
    System.out.println(email.getContent());
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

/**
 * {@inheritDoc}//  w  w w . j  a v a 2s.c o m
 */
@Override
public void send(final Email email) throws EmailException {

    if (email == null || ArrayUtils.isEmpty(email.getToAddresses())) {
        // does nothing.
        throw new EmailException("Email object null or invalid.");
    }

    // Simple email.
    final SimpleEmail simpleEmail = new SimpleEmail();

    // Mail content parameters.
    simpleEmail.setFrom(email.getFromAddress(), email.getFromName());
    for (final String address : email.getToAddresses()) {
        simpleEmail.addTo(address);
    }
    if (ArrayUtils.isNotEmpty(email.getCcAddresses())) {
        for (final String address : email.getCcAddresses()) {
            simpleEmail.addCc(address);
        }
    }
    simpleEmail.setSubject(email.getSubject());
    simpleEmail.setContent(email.getContent(), email.getContentType());

    // Mail sending parameters.
    simpleEmail.setCharset(email.getEncoding());
    simpleEmail.setHostName(email.getHostName());
    simpleEmail.setSmtpPort(email.getSmtpPort());

    // Authentication is needed.
    final String userName = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();
    if (userName != null && password != null) {
        simpleEmail.setAuthentication(userName, password);
    }

    // Sends the mail.
    simpleEmail.send();
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }/*w  w  w. ja v a  2  s  . c  o  m*/
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}