com.icegreen.greenmail.util.GreenMailUtil Java Examples

The following examples show how to use com.icegreen.greenmail.util.GreenMailUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 7 votes vote down vote up
@Test
public void htmlMessage() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  Session session = greenMail.getSmtp().createSession();
  MimeMessage message = MailTestUtil.createMimeMessageWithHtml(session);

  GreenMailUtil.sendMimeMessage(message);

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getHtml()).isEqualTo("<b>html</b>");
  assertThat(mail.getText()).isEqualTo("text");
}
 
Example #2
Source File: EmailReaderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testPopWait() throws Exception {
  BaleenCollectionReader bcr =
      getCollectionReader(
          EmailReader.PARAM_PROTOCOL, "pop3",
          EmailReader.PARAM_WAIT, 5,
          EmailReader.PARAM_SERVER, greenMail.getPop3().getBindTo(),
          EmailReader.PARAM_PORT, greenMail.getPop3().getPort(),
          EmailReader.PARAM_USER, "[email protected]",
          EmailReader.PARAM_PASS, "password",
          EmailReader.PARAM_PROCESS, "content");

  bcr.initialize();

  assertFalse(bcr.doHasNext());
  GreenMailUtil.sendTextEmailTest(
      "[email protected]", "[email protected]", GreenMailUtil.random(), GreenMailUtil.random());
  assertFalse(bcr.doHasNext()); // Should be a 5 second delay before it returns true

  Thread.sleep(5000);

  assertTrue(bcr.doHasNext());

  bcr.close();
}
 
Example #3
Source File: EmailSenderTest.java    From Spring-Boot-Examples with MIT License 6 votes vote down vote up
@Test
public void shouldSendEmail() throws Exception {
    // Given
    String to = "[email protected]";
    String from = "[email protected]";
    String title = "Title";
    String content = "Content";
    // When
    emailSender.sendEmail(to, from, title, content);
    // Then
    MimeMessage[] receivedMessages = server.getReceivedMessages();
    assertThat(receivedMessages.length).isEqualTo(1);

    MimeMessage receivedMessage = receivedMessages[0];
    assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(to); //to
    assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(from); //from
    assertThat(receivedMessage.getSubject()).isEqualTo(title); //title
    assertThat(receivedMessage.getContent().toString()).contains(content); //content
    //Or
    assertThat(content).isEqualTo(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #4
Source File: UserManagerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteUserShouldDeleteMail() throws Exception {
    ImapHostManager imapHostManager = new ImapHostManagerImpl(new InMemoryStore());
    UserManager userManager = new UserManager(imapHostManager);

    GreenMailUser user = userManager.createUser("[email protected]", "foo", "pwd");
    assertEquals(1, userManager.listUser().size());

    imapHostManager.createPrivateMailAccount(user);
    MailFolder otherfolder = imapHostManager.createMailbox(user, "otherfolder");
    MailFolder inbox = imapHostManager.getFolder(user, ImapConstants.INBOX_NAME);

    ServerSetup ss = ServerSetupTest.IMAP;
    MimeMessage m1 = GreenMailUtil.createTextEmail("there@localhost", "here@localhost", "sub1", "msg1", ss);
    MimeMessage m2 = GreenMailUtil.createTextEmail("there@localhost", "here@localhost", "sub1", "msg1", ss);

    inbox.store(m1);
    otherfolder.store(m2);
 
    userManager.deleteUser(user);
    assertTrue(imapHostManager.getAllMessages().isEmpty());
}
 
Example #5
Source File: SendMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void messageWithFileName() throws Exception {

 File attachment = new File(getClass().getResource("/attachment.txt").toURI());
 assertThat(attachment.exists()).isTrue();

 MailConnectors.sendMail()
    .createRequest()
      .from("test")
      .to("[email protected]")
      .subject("subject")
      .fileNames(attachment.getPath())
    .execute();

  MimeMessage[] mails = greenMail.getReceivedMessages();
  MimeMessage mail = mails[0];

  assertThat(mail.getContent()).isInstanceOf(MimeMultipart.class);
  MimeMultipart multiPart = (MimeMultipart) mail.getContent();

  assertThat(multiPart.getCount()).isEqualTo(1);
  assertThat(GreenMailUtil.getBody(multiPart.getBodyPart(0))).isEqualTo("plain text");
}
 
Example #6
Source File: PollMailConnectorProcessTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment(resources = "processes/mail-poll.bpmn")
public void pollMailWithTextBody() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "subject", "text body");

  ProcessInstance processInstance = engineRule.getRuntimeService().startProcessInstanceByKey("poll-mails");

  @SuppressWarnings("unchecked")
  List<Mail> mails = (List<Mail>) engineRule.getRuntimeService().getVariable(processInstance.getId(), "mails");

  assertThat(mails)
    .isNotNull()
    .hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getFrom()).isEqualTo("[email protected]");
  assertThat(mail.getSubject()).isEqualTo("subject");
  assertThat(mail.getText()).isEqualTo("text body");
}
 
Example #7
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void pollSingleMail() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "subject", "text body");

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getSubject()).isEqualTo("subject");
  assertThat(mail.getText()).isEqualTo("text body");
}
 
Example #8
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void dontPollDeletedMail() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "mail-1", "body");
  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "mail-2", "body");

  MailConnectors.deleteMails()
    .createRequest()
      .folder("INBOX")
      .messageNumbers(1)
    .execute();

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);
}
 
Example #9
Source File: DateTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testDatesCorrect() throws MessagingException, IOException {
    String to = "to@localhost";
    greenMail.setUser(to, to);

    // Create mail with specific 'sent' date
    final MimeMessage mail = GreenMailUtil.createTextEmail(to, "from@localhost", "Subject", "msg", greenMail.getSmtp().getServerSetup());
    final Date sentDate = new GregorianCalendar(2000, 1, 1, 0, 0, 0).getTime();
    mail.setSentDate(sentDate);
    GreenMailUtil.sendMimeMessage(mail);

    greenMail.waitForIncomingEmail(5000, 1);

    retrieveAndCheck(greenMail.getPop3(), to, sentDate, false);
    retrieveAndCheck(greenMail.getImap(), to, sentDate, true);
}
 
Example #10
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void messageWithAttachment() throws Exception {
  File attachment = new File(getClass().getResource("/attachment.txt").toURI());
  assertThat(attachment.exists()).isTrue();

  greenMail.setUser("[email protected]", "bpmn");

  Session session = greenMail.getSmtp().createSession();
  MimeMessage message = MailTestUtil.createMimeMessageWithAttachment(session, attachment);
  GreenMailUtil.sendMimeMessage(message);

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getAttachments()).hasSize(1);

  Attachment mailAttachment = mail.getAttachments().get(0);
  assertThat(mailAttachment.getFileName()).isEqualTo("attachment.txt");
  assertThat(mailAttachment.getPath()).isNotNull();
}
 
Example #11
Source File: AuthenticationDisabledTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMailAndReceiveWithAuthDisabled() throws MessagingException, IOException {
    final String to = "to@localhost";
    final String subject = "subject";
    final String body = "body";
    GreenMailUtil.sendTextEmailTest(to, "from@localhost", subject, body);
    MimeMessage[] emails = greenMail.getReceivedMessages();
    assertEquals(1, emails.length);
    assertEquals(subject, emails[0].getSubject());
    assertEquals(body, GreenMailUtil.getBody(emails[0]));

    greenMail.waitForIncomingEmail(5000, 1);

    try (Retriever retriever = new Retriever(greenMail.getImap())) {
        Message[] messages = retriever.getMessages(to);
        assertEquals(1, messages.length);
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, messages[0].getContent());
    }
}
 
Example #12
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void pollMultipleMails() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "mail-1", "body");
  GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "mail-2", "body");

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails)
    .hasSize(2)
    .extracting("subject")
    .contains("mail-1", "mail-2");
}
 
Example #13
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
Example #14
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetreiveSimpleWithNonDefaultPassword() throws Exception {
    assertNotNull(greenMail.getImap());
    final String to = "[email protected]";
    final String password = "donotharmanddontrecipricateharm";
    greenMail.setUser(to, password);
    final String subject = GreenMailUtil.random();
    final String body = GreenMailUtil.random();
    GreenMailUtil.sendTextEmailTest(to, "from@localhost", subject, body);
    greenMail.waitForIncomingEmail(5000, 1);

    try (Retriever retriever = new Retriever(greenMail.getImap())) {
        try {
            retriever.getMessages(to, "wrongpassword");
            fail("Expected failed login");
        } catch (Throwable e) {
            // ok
        }

        Message[] messages = retriever.getMessages(to, password);
        assertEquals(1, messages.length);
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, ((String) messages[0].getContent()).trim());
    }
}
 
Example #15
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testImapsReceive() throws Throwable {
    assertNotNull(greenMail.getImaps());
    final String subject = GreenMailUtil.random();
    final String body = GreenMailUtil.random();
    String to = "test@localhost";
    GreenMailUtil.sendTextEmailSecureTest(to, "from@localhost", subject, body);
    greenMail.waitForIncomingEmail(5000, 1);

    try (Retriever retriever = new Retriever(greenMail.getImaps())) {
        Message[] messages = retriever.getMessages(to);
        assertEquals(1, messages.length);
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, ((String) messages[0].getContent()).trim());
    }
}
 
Example #16
Source File: RetrCommand.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Pop3Connection conn, Pop3State state,
                    String cmd) {
    try {
        MailFolder inbox = state.getFolder();
        String[] cmdLine = cmd.split(" ");

        String msgNumStr = cmdLine[1];
        List<StoredMessage> msgList = inbox.getMessages(new MsgRangeFilter(msgNumStr, false));
        if (msgList.size() != 1) {
            conn.println("-ERR no such message");

            return;
        }

        StoredMessage msg = msgList.get(0);
        String email = GreenMailUtil.getWholeMessage(msg.getMimeMessage());
        conn.println("+OK");
        conn.print(new StringReader(email));
        conn.println();
        conn.println(".");
        msg.setFlag(Flags.Flag.SEEN, true);
    } catch (Exception e) {
        conn.println("-ERR " + e);
    }
}
 
Example #17
Source File: MailNotificationServiceTest.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
@Test
public void messageHandler() throws Exception {
	GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "existing mail", "body");

	notificationService.start();

	final List<Message> receivedMessages = new ArrayList<>();
	final CountDownLatch countDownLatch = new CountDownLatch(1);

	notificationService.registerMessageHandler(messages -> {
		receivedMessages.addAll(messages);
		countDownLatch.countDown();
	});

	GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "new mail", "body");

	countDownLatch.await(10, TimeUnit.SECONDS);

	assertThat(receivedMessages).hasSize(1);
}
 
Example #18
Source File: MovingMessage.java    From greenmail with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the contents of the stream until
 * &lt;CRLF&gt;.&lt;CRLF&gt; is encountered.
 * <p/>
 * <p/>
 * It would be possible and perhaps desirable to prevent the
 * adding of an unnecessary CRLF at the end of the message, but
 * it hardly seems worth 30 seconds of effort.
 * </p>
 */
public void readDotTerminatedContent(BufferedReader in)
        throws IOException {
    StringBuilder buf = new StringBuilder();

    while (true) {
        String line = in.readLine();
        if (line == null)
            throw new EOFException("Did not receive <CRLF>.<CRLF>");

        if (".".equals(line)) {
            break;
        } else if (line.startsWith(".")) {
            println(buf, line.substring(1));
        } else {
            println(buf, line);
        }
    }
    content = buf.toString();
    try {
        message = GreenMailUtil.newMimeMessage(content);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: Pop3ServerTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrieveWithNonDefaultPassword() throws Exception {
    assertNotNull(greenMail.getPop3());
    final String to = "[email protected]";
    final String password = "donotharmanddontrecipricateharm";
    greenMail.setUser(to, password);
    final String subject = GreenMailUtil.random();
    final String body = GreenMailUtil.random();
    GreenMailUtil.sendTextEmailTest(to, "[email protected]", subject, body);
    greenMail.waitForIncomingEmail(5000, 1);

    try (Retriever retriever = new Retriever(greenMail.getPop3())) {
        try {
            retriever.getMessages(to, "wrongpassword");
            fail("Expected authentication failure");
        } catch (Throwable e) {
            // ok
        }

        Message[] messages = retriever.getMessages(to, password);
        assertEquals(1, messages.length);
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, GreenMailUtil.getBody(messages[0]).trim());
    }
}
 
Example #20
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmailNotifierRunError() throws Exception {

  EmailNotifier emailNotifier = new EmailNotifier("x", "x", "0", runtimeInfo, emailSender, ImmutableList.of("foo", "bar"),
    ImmutableSet.of("RUN_ERROR"));

  PipelineState runningState = new PipelineStateImpl("x", "x", "0", PipelineStatus.RUNNING, "Running",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  PipelineState runErrorState = new PipelineStateImpl("x", "x", "0", PipelineStatus.RUN_ERROR, "Run Error",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  emailNotifier.onStateChange(runningState, runErrorState, "", null, null);

  String headers = GreenMailUtil.getHeaders(server.getReceivedMessages()[0]);
  Assert.assertTrue(headers != null);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - x - ERROR"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #21
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmailNotifierStartError() throws Exception {

  EmailNotifier emailNotifier = new EmailNotifier("x", "x","0", runtimeInfo, emailSender, ImmutableList.of("foo", "bar")
    , ImmutableSet.of("START_ERROR"));

  PipelineState startingState = new PipelineStateImpl("x", "x", "0", PipelineStatus.STARTING, "Starting",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  PipelineState startErrorState = new PipelineStateImpl("x", "x", "0", PipelineStatus.START_ERROR, "Start Error",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  emailNotifier.onStateChange(startingState, startErrorState, "", null, null);

  String headers = GreenMailUtil.getHeaders(server.getReceivedMessages()[0]);
  Assert.assertTrue(headers != null);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - x - ERROR"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #22
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * 一个附件的邮件测试
 * 
 * @throws MessagingException
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testSendMailFiles() throws MessagingException, InterruptedException, IOException {
    SimpleMailMessage message = buildSimpleMessage();
    String[] files = new String[] { EMAIL_ATTACHMENT };
    mimeMailService.sendMailFiles(message, files);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertEquals(2, mimeMultipart.getCount());//multipart个数
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
    assertEquals("Hello,i am a attachment.", GreenMailUtil
            .getBody(mimeMultipart.getBodyPart(1)).trim());
}
 
Example #23
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmailNotifierStopped() throws Exception {

  EmailNotifier emailNotifier = new EmailNotifier("x", "x","0", runtimeInfo, emailSender, ImmutableList.of("foo", "bar"),
    ImmutableSet.of("STOPPED"));

  PipelineState stoppingState = new PipelineStateImpl("x", "x", "0", PipelineStatus.STOPPING, "Stopping",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  PipelineState stoppedState = new PipelineStateImpl("x", "x", "0", PipelineStatus.STOPPED, "Stopped",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  emailNotifier.onStateChange(stoppingState, stoppedState, "", null, null);

  String headers = GreenMailUtil.getHeaders(server.getReceivedMessages()[0]);
  Assert.assertTrue(headers != null);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - x - STOPPED"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #24
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmailNotifierDisconnected() throws Exception {

  EmailNotifier emailNotifier = new EmailNotifier("x", "x","0", runtimeInfo, emailSender, ImmutableList.of("foo", "bar"),
    ImmutableSet.of("DISCONNECTED"));

  PipelineState disconnectingState = new PipelineStateImpl("x", "x", "0", PipelineStatus.DISCONNECTING, "Disconnecting",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  PipelineState disconnectedState = new PipelineStateImpl("x", "x", "0", PipelineStatus.DISCONNECTED, "Disconnected",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  emailNotifier.onStateChange(disconnectingState, disconnectedState, "", null, null);

  String headers = GreenMailUtil.getHeaders(server.getReceivedMessages()[0]);
  Assert.assertTrue(headers != null);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - x - DISCONNECTED"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #25
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmailNotifierConnecting() throws Exception {

  EmailNotifier emailNotifier = new EmailNotifier("x", "x","0", runtimeInfo, emailSender, ImmutableList.of("foo", "bar"),
    ImmutableSet.of("CONNECTING"));

  PipelineState disconnectedState = new PipelineStateImpl("x", "x", "0", PipelineStatus.DISCONNECTED, "Disconnected",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  PipelineState connectingState = new PipelineStateImpl("x", "x", "0", PipelineStatus.CONNECTING, "Connecting",
    System.currentTimeMillis(), new HashMap<String, Object>(), ExecutionMode.STANDALONE, "", 0, 0);
  emailNotifier.onStateChange(disconnectedState, connectingState, "", null, null);

  String headers = GreenMailUtil.getHeaders(server.getReceivedMessages()[0]);
  Assert.assertTrue(headers != null);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - x - CONNECTING"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(server.getReceivedMessages()[0]));
}
 
Example #26
Source File: TestStandaloneRunner.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testPipelineStoppedWithMail() throws Exception {
  Runner runner = pipelineManager.getRunner( TestUtil.PIPELINE_WITH_EMAIL, "0");
  runner.start(new StartPipelineContextBuilder("admin").build());
  waitForState(runner, PipelineStatus.RUNNING);
  runner.getRunner(AsyncRunner.class).getDelegatingRunner().prepareForStop("admin");
  runner.getRunner(AsyncRunner.class).getDelegatingRunner().stop("admin");
  waitForState(runner, PipelineStatus.STOPPED);
  //wait for email
  GreenMail mailServer = TestUtil.TestRuntimeModule.getMailServer();
  while(mailServer.getReceivedMessages().length < 1) {
    ThreadUtil.sleep(100);
  }
  String headers = GreenMailUtil.getHeaders(mailServer.getReceivedMessages()[0]);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - " +
      TestUtil.PIPELINE_TITLE_WITH_EMAIL + " - STOPPED"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(mailServer.getReceivedMessages()[0]));

  mailServer.reset();
}
 
Example #27
Source File: TestStandaloneRunner.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testPipelineFinishWithMail() throws Exception {
  Runner runner = pipelineManager.getRunner( TestUtil.PIPELINE_WITH_EMAIL, "0");
  runner.start(new StartPipelineContextBuilder("admin").build());
  waitForState(runner, PipelineStatus.RUNNING);
  assertNull(runner.getState().getMetrics());
  TestUtil.EMPTY_OFFSET = true;
  waitForState(runner, PipelineStatus.FINISHED);
  assertNotNull(runner.getState().getMetrics());
  //wait for email
  GreenMail mailServer = TestUtil.TestRuntimeModule.getMailServer();
  while(mailServer.getReceivedMessages().length < 1) {
    ThreadUtil.sleep(100);
  }
  String headers = GreenMailUtil.getHeaders(mailServer.getReceivedMessages()[0]);
  Assert.assertTrue(headers.contains("To: foo, bar"));
  Assert.assertTrue(headers.contains("Subject: StreamsSets Data Collector Alert - " +
      TestUtil.PIPELINE_TITLE_WITH_EMAIL + " - FINISHED"));
  Assert.assertTrue(headers.contains("From: sdc@localhost"));
  Assert.assertNotNull(GreenMailUtil.getBody(mailServer.getReceivedMessages()[0]));

  mailServer.reset();
}
 
Example #28
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * 邮件模板测试,不含附件
 * 
 * @throws MessagingException
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testSendMailTemplate() throws MessagingException, InterruptedException, IOException {
    SimpleMailMessage message = buildSimpleMessage();
    String filename = "mailTemplate.ftl";
    Map<String, String> params = Collections.singletonMap("userName", MAIL_MESSAGE_TO);
    mimeMailService.sendMailTemplate(message, filename, params);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_TO));
}
 
Example #29
Source File: SendReceiveWithInternationalAddressTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws MessagingException, UnsupportedEncodingException {

    Session session = GreenMailUtil.getSession(ServerSetupTest.SMTP, properties);
    MimeMessage mimeMessage = new MockInternationalizedMimeMessage(session);
    mimeMessage.setSubject("subject");
    mimeMessage.setSentDate(new Date());
    mimeMessage.setFrom("múchätįldé@tìldę.oœ");
    mimeMessage.setRecipients(Message.RecipientType.TO, "用户@例子.广告");
    mimeMessage.setRecipients(Message.RecipientType.CC, "θσερεχα@μπλε.ψομ");
    mimeMessage.setRecipients(Message.RecipientType.BCC, "राममो@हन.ईन्फो");

    // The body text needs to be encoded if it contains non us-ascii characters
    mimeMessage.setText(MimeUtility.encodeText("用户@例子"));

    GreenMailUtil.sendMimeMessage(mimeMessage);

    // Decoding the body text to verify equality
    String decodedText = MimeUtility.decodeText(GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]));
    assertEquals("用户@例子", decodedText);
}
 
Example #30
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * MimeMessage格式邮件发送
 * 
 * @throws Exception
 */
@Test
public void testSendMail() throws Exception {
    SimpleMailMessage message = buildSimpleMessage();
    mimeMailService.sendMail(message);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
}