Example usage for javax.mail.internet MimeMessage getRecipients

List of usage examples for javax.mail.internet MimeMessage getRecipients

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getRecipients.

Prototype

@Override
public Address[] getRecipients(Message.RecipientType type) throws MessagingException 

Source Link

Document

Returns the recepients specified by the type.

Usage

From source file:com.thoughtworks.go.config.GoSmtpMailSender.java

public ValidationBean send(String subject, String body, String to) {
    Transport transport = null;/*from w w w  .j  a  v  a  2  s.  co  m*/
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Sending email [%s] to [%s]", subject, to));
        }
        Properties props = mailProperties();
        MailSession session = MailSession.getInstance().createWith(props, username, password);
        transport = session.getTransport();
        transport.connect(host, port, nullIfEmpty(username), nullIfEmpty(password));
        MimeMessage msg = session.createMessage(from, to, subject, body);
        transport.sendMessage(msg, msg.getRecipients(TO));
        return ValidationBean.valid();
    } catch (AuthenticationFailedException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: Authentication failed");
    } catch (NoSuchProviderException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (MessagingException e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } catch (Exception e) {
        LOGGER.error(String.format("Sending failed for email [%s] to [%s]", subject, to), e);
        return ValidationBean.notValid("Failed to send the email. Caused by: " + e.getMessage());
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                LOGGER.error("Failed to close transport", e);
            }
        }
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private String getPrimaryAddressee(final MimeMessage mimeMessage) throws MessagingException {
    final Address[] recipients = mimeMessage.getRecipients(RecipientType.TO);
    return recipients != null && recipients.length > 0 ? recipients[0].toString() : "?";
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private String[] getCCAddressees(final MimeMessage mimeMessage) throws MessagingException {
    final Address[] recipients = mimeMessage.getRecipients(RecipientType.CC);
    if (recipients == null) {
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }/*  w w w . j a  v a  2s.com*/
    final String[] result = new String[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        result[i] = recipients[i].toString();
    }
    return result;
}

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

public void testMimeMessageHelper() throws AddressException, IOException, MessagingException {

    String message = "Hello MimeMessageHelper";
    String from = "r.lagrotteria@greenvulcano.com";
    String to = "hr@greenvulcano.com";

    String attachemnt1 = Base64.encodeBase64String("test1111111111".getBytes());
    String attachemnt2 = Base64.encodeBase64String("test2222222222".getBytes());

    String email = MimeMessageHelper.createEmailMessage(from, to).setTextBody(message)
            .addAttachment("test1.txt", "text/plain", attachemnt1)
            .addAttachment("test2.txt", "text/plain", attachemnt2).getEncodedMimeMessage();

    MimeMessage mimeMessage = MimeMessageHelper.decode(email);

    assertEquals(from, mimeMessage.getFrom()[0].toString());
    assertEquals(to, mimeMessage.getRecipients(RecipientType.TO)[0].toString());

    List<MimeMessageHelper.Attachment> attachments = MimeMessageHelper.getMessageAttachments(mimeMessage);

    assertEquals(2, attachments.size());

    assertEquals(attachemnt2, attachments.stream().filter(a -> a.getFileName().equals("test2.txt"))
            .map(a -> a.getContent()).findFirst().get());

    assertEquals("hr@greenvulcano.com", MimeMessageHelper.getMessageRecipients(mimeMessage).get("TO").get(0));
    assertEquals("Hello MimeMessageHelper", MimeMessageHelper.getMessageBody(mimeMessage).getContent());

    email = MimeMessageHelper.createEmailMessage(from, to).setTextBody(message).getEncodedMimeMessage();

    assertEquals("Hello MimeMessageHelper", MimeMessageHelper.getMessageBody(mimeMessage).getContent());

}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException {
    // get information about the original message.
    Address[] originalFromRecipient = message.getFrom();
    Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO);
    Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC);
    Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC);
    String originalSubject = message.getSubject();

    // create the html for the string buffer.
    StringBuffer html = new StringBuffer();
    html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>");
    html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>");

    // iterate over the addresses.
    if (originalFromRecipient != null) {
        for (int i = 0; i < originalFromRecipient.length; i++) {
            html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>");
        }// ww w  .  j av a 2s  .co m
    }
    if (originalToRecipient != null) {
        for (int i = 0; i < originalToRecipient.length; i++) {
            html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>");
        }
    }
    if (originalCcRecipient != null) {
        for (int i = 0; i < originalCcRecipient.length; i++) {
            html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>");
        }
    }
    if (originalBccRecipient != null) {
        for (int i = 0; i < originalBccRecipient.length; i++) {
            html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>");
        }
    }
    html.append("</table></body></html>");

    MimeBodyPart sentToBodyPart = new MimeBodyPart();
    sentToBodyPart.setContent(html.toString(), "text/html");
    sentToBodyPart.setHeader("Content-ID", "original-addresses");
    sentToBodyPart.setDisposition("inline");

    return sentToBodyPart;
}

From source file:cherry.foundation.mail.MailSendHandlerImplTest.java

@Test
public void testSendNowAttached() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    MailSendHandler handler = create(now);

    ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class);
    doNothing().when(mailSender).send(preparator.capture());

    final File file = File.createTempFile("test_", ".txt", new File("."));
    file.deleteOnExit();/*from w  w  w. j a  v  a  2 s.c o m*/
    try {

        try (OutputStream out = new FileOutputStream(file)) {
            out.write("attach2".getBytes());
        }

        final DataSource dataSource = new DataSource() {
            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getName() {
                return "name3.txt";
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream("attach3".getBytes());
            }

            @Override
            public String getContentType() {
                return "text/plain";
            }
        };

        long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"),
                asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() {
                    @Override
                    public void prepare(Attachment attachment) throws MessagingException {
                        attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes()));
                        attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()),
                                "application/octet-stream");
                        attachment.add("name2.txt", file);
                        attachment.add("name3.txt", dataSource);
                    }
                });

        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);
        preparator.getValue().prepare(message);

        assertEquals(0L, messageId);
        assertEquals(1, message.getRecipients(RecipientType.TO).length);
        assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]);
        assertEquals(1, message.getRecipients(RecipientType.CC).length);
        assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]);
        assertEquals(1, message.getRecipients(RecipientType.BCC).length);
        assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]);
        assertEquals(1, message.getFrom().length);
        assertEquals(parse("from@addr")[0], message.getFrom()[0]);
        assertEquals("subject", message.getSubject());

        MimeMultipart mm = (MimeMultipart) message.getContent();
        assertEquals(5, mm.getCount());
        assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent());

        assertEquals("name0.txt", mm.getBodyPart(1).getFileName());
        assertEquals("text/plain", mm.getBodyPart(1).getContentType());
        assertEquals("attach0", mm.getBodyPart(1).getContent());

        assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName());
        assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType());
        assertEquals("attach1", new String(
                ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent())));

        assertEquals("name2.txt", mm.getBodyPart(3).getFileName());
        assertEquals("text/plain", mm.getBodyPart(3).getContentType());
        assertEquals("attach2", mm.getBodyPart(3).getContent());

        assertEquals("name3.txt", mm.getBodyPart(4).getFileName());
        assertEquals("text/plain", mm.getBodyPart(4).getContentType());
        assertEquals("attach3", mm.getBodyPart(4).getContent());
    } finally {
        file.delete();
    }
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessage() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTest", ".eml");

    outputFile.deleteOnExit();/* w ww.j a  v  a 2s  .  c  om*/

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessage(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();/*  w  w w.  j  a  v a  2  s .c o  m*/

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:com.gcrm.util.mail.MailService.java

public void sendSystemSimpleMail(String toAddress, String subject, String text) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;//w w  w  .  java2  s .  co  m
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    Session mailSession = this.createSmtpSession(emailSetting);
    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(emailSetting.getFrom_address());
        helper.setTo(toAddress);
        helper.setSubject(subject);
        helper.setText(text, true);
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }
}

From source file:com.gcrm.util.mail.MailService.java

public void sendSimpleMail(String toAddress) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;/*  w w  w  .j a va  2  s  .  c o m*/
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    Session mailSession = this.createSmtpSession(emailSetting);
    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(emailSetting.getFrom_address());
        helper.setTo(toAddress);
        helper.setSubject("Test Mail From " + emailSetting.getFrom_name());
        helper.setText("This is test mail from " + emailSetting.getFrom_name(), true);
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }
}