Example usage for javax.mail.internet MimeMessage getAllRecipients

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

Introduction

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

Prototype

@Override
public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

From source file:com.haulmont.cuba.core.app.EmailerTest.java

@Test
public void testSendAllToAdmin() throws Exception {
    emailerConfig.setSendAllToAdmin(true);
    emailerConfig.setAdminAddress("admin@example.com");
    try {//from ww  w .  j  a  v  a2  s  .c  o m
        emailer.sendEmail("michael@example.com", "Test Email 5", "Test Body 5");

        emailer.sendEmailAsync(new EmailInfo("nikolay@example.com", "Test Email 6", "Test Body 6"));
        emailer.processQueuedEmails();

        for (int i = 0; i < 2; i++) {
            MimeMessage msg = testMailSender.fetchSentEmail();
            assertEquals(1, msg.getAllRecipients().length);
            assertEquals("admin@example.com", msg.getAllRecipients()[0].toString());
        }

    } finally {
        emailerConfig.setSendAllToAdmin(false);
    }
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void authLogin() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250-smtp.zimbra.com").sendLine("250 AUTH LOGIN").recvLine() // AUTH LOGIN
            .sendLine("334 OK").recvLine() // USER
            .sendLine("334").recvLine() // PASSWORD
            .sendLine("235 Authentication successful").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("250 OK").recvLine() // DATA
            .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT
            .sendLine("221 bye").build().start(PORT);

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, "zimbra", "secret");
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();/*from   w w  w.  j  a va 2s  . c  o m*/

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("AUTH LOGIN\r\n", server.replay());
    Assert.assertEquals(base64("zimbra") + "\r\n", server.replay());
    Assert.assertEquals(base64("secret") + "\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private void doTestAsynchronous(boolean useFs) throws Exception {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();//from  ww  w  . j  a va2s  .co  m

    String body = "Test Email Body";
    EmailInfo myInfo = new EmailInfo("recipient@example.com", "Test", body);
    List<SendingMessage> messages = emailer.sendEmailAsync(myInfo);
    assertEquals(1, messages.size());

    // not sent yet
    assertTrue(testMailSender.isEmpty());
    SendingMessage sendingMsg = reload(messages.get(0));
    assertEquals(SendingStatus.QUEUE, sendingMsg.getStatus());

    // run scheduler
    emailer.processQueuedEmails();

    // check
    assertEquals(1, testMailSender.getBufferSize());
    MimeMessage msg = testMailSender.fetchSentEmail();

    assertEquals(1, msg.getAllRecipients().length);
    assertEquals("recipient@example.com", msg.getAllRecipients()[0].toString());

    assertEquals("Test", msg.getSubject());
    assertEquals(body, getBody(msg));
    assertTrue(getBodyContentType(msg).startsWith("text/plain;"));

    sendingMsg = reload(messages.get(0));
    assertEquals(SendingStatus.SENT, sendingMsg.getStatus());
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private void doTestSeveralRecipients(boolean useFs) throws MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();//w  w w. j a  va2 s .c o m

    String body = "Test Email Body";
    String recipients = "misha@example.com,kolya@example.com;tanya@example.com;"; // 3 recipients
    EmailInfo myInfo = new EmailInfo(recipients, "Test", body);
    List<SendingMessage> messages = emailer.sendEmailAsync(myInfo);
    assertEquals(3, messages.size());

    assertTrue(testMailSender.isEmpty());
    emailer.processQueuedEmails();

    Set<String> recipientSet = new HashSet<>();
    // check
    assertEquals(3, testMailSender.getBufferSize());
    for (int i = 0; i < 3; i++) {
        MimeMessage msg = testMailSender.fetchSentEmail();
        Address[] msgRecipients = msg.getAllRecipients();
        assertEquals(1, msgRecipients.length);
        recipientSet.add(msgRecipients[0].toString());
    }

    assertTrue(recipientSet.contains("misha@example.com"));
    assertTrue(recipientSet.contains("kolya@example.com"));
    assertTrue(recipientSet.contains("tanya@example.com"));
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilderTest.java

@Test
public void test_construction() throws Exception {
    MimeMessageBuilder messageBuilder = new MimeMessageBuilder();

    messageBuilder.addRecipients("tom.xxxx@gmail.com, tom.yyyy@gmail.com");
    MimeMessage mimeMessage = messageBuilder.buildMimeMessage();

    // check from and reply-to
    Address[] from = mimeMessage.getFrom();
    Assert.assertNotNull(from);//from   w  w  w. j  av a  2 s. co  m
    Assert.assertEquals(1, from.length);
    Assert.assertEquals(A, from[0].toString());
    Address[] replyTo = mimeMessage.getReplyTo();
    Assert.assertNotNull(from);
    Assert.assertEquals(1, replyTo.length);
    Assert.assertEquals(A, replyTo[0].toString());

    // check the recipient list...
    Address[] allRecipients = mimeMessage.getAllRecipients();
    Assert.assertNotNull(allRecipients);
    Assert.assertEquals(2, allRecipients.length);
    Assert.assertEquals(X, allRecipients[0].toString());
    Assert.assertEquals(Y, allRecipients[1].toString());

    // Make sure we can regen the instance identifier public key
    String encodedIdent = mimeMessage.getHeader("X-Instance-Identity")[0];
    byte[] image = Base64.decodeBase64(encodedIdent);
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(image));
    Assert.assertNotNull(publicKey);
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void mailFromError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("451 error").recvLine() // QUIT
            .build().start(PORT);/*from w  ww. ja va  2 s  . co m*/

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\n" + "Subject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(0, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(0, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:edu.stanford.muse.util.EmailUtils.java

/**
 * best effort to toString something about the given message.
 * use only for diagnostics, not for user-visible messages.
 * treads defensively, this can be called to report on a badly formatted message.
 *///from  w ww .ja v  a 2  s. c  o  m
public static String formatMessageHeader(MimeMessage m) throws MessagingException {
    StringBuilder sb = new StringBuilder();
    sb.append("To: ");
    if (m == null) {
        log.warn("Trying to format null message!?");
        return "Null message";
    }
    try {
        Address[] tos = m.getAllRecipients();
        if (tos != null)
            for (Address a : tos)
                sb.append(a.toString() + " ");
        sb.append("\n");
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    sb.append("From: ");
    try {
        Address[] froms = m.getFrom();
        if (froms != null)
            for (Address a : froms)
                sb.append(a.toString() + " ");
        sb.append("\n");
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    try {
        sb.append("Subject: " + m.getSubject());
        sb.append("Message-ID: " + m.getMessageID());
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    return sb.toString();
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void rcptToError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("550 error").recvLine() // QUIT
            .build().start(PORT);//  w  ww. ja v a2s  .c o  m

    Session session = JMSession.getSession();
    session.getProperties().setProperty("mail.smtp.sendpartial", "true");
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(0, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(1, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void dataError() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("250 OK").recvLine() // DATA
            .sendLine("451 error").recvLine() // QUIT
            .build().start(PORT);//from  w w w .  j av a 2s.  c o m

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    try {
        transport.sendMessage(msg, msg.getAllRecipients());
        Assert.fail();
    } catch (SendFailedException e) {
        Assert.assertEquals(1, e.getValidSentAddresses().length);
        Assert.assertEquals(0, e.getValidUnsentAddresses().length);
        Assert.assertEquals(0, e.getInvalidAddresses().length);
    } finally {
        transport.close();
    }

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

/**
 * Actually send the given array of MimeMessages via JavaMail.
 * @param mimeMessages MimeMessage objects to send
 * @param originalMessages corresponding original message objects
 * that the MimeMessages have been created from (with same array
 * length and indices as the "mimeMessages" array), if any
 * @throws org.springframework.mail.MailAuthenticationException
 * in case of authentication failure//w  w w. j a v  a 2 s.c  om
 * @throws org.springframework.mail.MailSendException
 * in case of failure when sending a message
 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map failedMessages = new HashMap();
    try {
        Transport transport = getTransport(getSession());
        transport.connect(getHost(), getPort(), getUsername(), getPassword());
        try {
            for (int i = 0; i < mimeMessages.length; i++) {
                MimeMessage mimeMessage = mimeMessages[i];
                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }
                    mimeMessage.saveChanges();
                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (MessagingException ex) {
                    Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                    failedMessages.put(original, ex);
                }
            }
        } finally {
            transport.close();
        }
    } catch (AuthenticationFailedException ex) {
        throw new MailAuthenticationException(ex);
    } catch (MessagingException ex) {
        throw new MailSendException("Mail server connection failed", ex);
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}