Example usage for javax.mail.internet MimeMessage getFrom

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

Introduction

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

Prototype

@Override
public Address[] getFrom() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "From" header fields.

Usage

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyTemplate() throws Exception {
    Map<String, Object> model = Collections.<String, Object>singletonMap("name", "John Doe");
    String body = processTemplate(TEMPLATE_NAME, model);

    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, TEMPLATE_NAME,
            model, false);// w w w.ja v  a2  s  .co  m

    assertNotNull(email);

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(body, msg.getContent());
}

From source file:org.sonarqube.tests.settings.EmailsTest.java

@Test
public void send_test_email() throws Exception {
    updateEmailSettings("localhost", Integer.toString(SMTP_SERVER.getServer().getPort()), null, null, null,
            null, null, null);//from   w ww  . j a  v a  2  s  .  co m

    sendEmail("test@example.org", "Test Message from SonarQube", "This is a test message from SonarQube");

    // We need to wait until all notifications will be delivered
    waitUntilAllNotificationsAreDelivered(1);
    Iterator<WiserMessage> emails = SMTP_SERVER.getMessages().iterator();
    MimeMessage message = emails.next().getMimeMessage();
    assertThat(Arrays.stream(message.getFrom()).map(Address::toString))
            .containsOnly("SonarQube <noreply@nowhere>");
    assertThat(message.getHeader("To", null)).isEqualTo("<test@example.org>");
    assertThat(message.getSubject()).isEqualTo("[SONARQUBE] Test Message from SonarQube");
    assertThat((String) message.getContent()).contains("This is a test message from SonarQube");
    assertThat(emails.hasNext()).isFalse();
}

From source file:org.sonarqube.tests.settings.EmailsTest.java

@Test
public void send_customized_test_email() throws Exception {
    String from = randomAlphanumeric(4) + "@" + randomAlphabetic(5);
    String fromName = randomAlphanumeric(5);
    String prefix = randomAlphanumeric(6);
    updateEmailSettings("localhost", Integer.toString(SMTP_SERVER.getServer().getPort()), from, fromName,
            prefix, null, null, null);//from  ww w.  j av a  2s .c om

    sendEmail("test@example.org", "Test Message from SonarQube", "This is a test message from SonarQube");

    // We need to wait until all notifications will be delivered
    waitUntilAllNotificationsAreDelivered(1);
    Iterator<WiserMessage> emails = SMTP_SERVER.getMessages().iterator();
    MimeMessage message = emails.next().getMimeMessage();
    assertThat(Arrays.stream(message.getFrom()).map(Address::toString))
            .containsOnly(format("%s <%s>", fromName, from));
    assertThat(message.getHeader("To", null)).isEqualTo("<test@example.org>");
    assertThat(message.getSubject()).isEqualTo(prefix + " Test Message from SonarQube");
    assertThat((String) message.getContent()).contains("This is a test message from SonarQube");
    assertThat(emails.hasNext()).isFalse();
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }//from  ww w.j  a  v a 2 s .c  o  m

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:org.xwiki.mail.internal.DefaultMailSender.java

@Override
public void sendAsynchronously(MimeMessage message, Session session, MailResultListener listener) {
    try {/* w  w w. j ava 2  s. c  om*/
        // Perform some basic verification to avoid NPEs in JavaMail
        if (message.getFrom() == null) {
            // Try using the From address in the Session
            String from = this.configuration.getFromAddress();
            if (from != null) {
                message.setFrom(new InternetAddress(from));
            } else {
                throw new MessagingException("Missing the From Address for sending the mail. "
                        + "You need to either define it in the Mail Configuration or pass it in your message.");
            }
        }

        // Push new mail message on the queue
        getMailQueue().add(new MailSenderQueueItem(message, session, listener));
    } catch (Exception e) {
        // Save any exception in the listener
        listener.onError(message, e);
    }
}

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   www .jav  a 2s  .  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: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:org.mobicents.servlet.restcomm.email.EmailServiceTest.java

@Test
public void testSendEmail() {
    new JavaTestKit(system) {
        {// w w  w  . java 2  s . co  m
            final ActorRef observer = getRef();

            // Send the email.
            final Mail emailMsg = new Mail("hascode@localhost", "someone@localhost.com",
                    "Testing Email Service", "This is the subject of the email service testing",
                    "someone2@localhost.com, test@localhost.com, test3@localhost.com",
                    "someone3@localhost.com, test2@localhost.com");
            emailService.tell(new EmailRequest(emailMsg), observer);

            final EmailResponse response = expectMsgClass(FiniteDuration.create(60, TimeUnit.SECONDS),
                    EmailResponse.class);
            assertTrue(response.succeeded());

            // fetch messages from server
            MimeMessage[] messages = mailServer.getReceivedMessages();
            assertNotNull(messages);
            assertEquals(6, messages.length);
            MimeMessage m = messages[0];
            try {
                assertEquals(emailMsg.subject(), m.getSubject());
                assertTrue(String.valueOf(m.getContent()).contains(emailMsg.body()));
                assertEquals(emailMsg.from(), m.getFrom()[0].toString());
            } catch (Exception e) {
                assertTrue(false);
            }
        }
    };
}

From source file:io.lavagna.service.MailTicketService.java

private String getFrom(MimeMessage message) throws MessagingException {
    Address[] froms = message.getFrom();
    return froms == null ? null : ((InternetAddress) froms[0]).getAddress();
}

From source file:io.lavagna.service.MailTicketService.java

private String getName(MimeMessage message) throws MessagingException {
    Address[] froms = message.getFrom();
    return froms == null ? null : ((InternetAddress) froms[0]).getPersonal();
}