com.icegreen.greenmail.util.GreenMail Java Examples

The following examples show how to use com.icegreen.greenmail.util.GreenMail. 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: GreenMailRule.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            greenMail = new GreenMail(serverSetups);
            try {
                start();
                base.evaluate();
            } finally {
                stop();
            }
        }

    };
}
 
Example #2
Source File: SshdShellAutoConfigurationTest.java    From sshd-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthInfoCommand() {
    int smtpPort = SocketUtils.findAvailableTcpPort();
    ServerSetup setup = new ServerSetup(smtpPort, null, ServerSetup.PROTOCOL_SMTP);
    setup.setServerStartupTimeout(5000);
    GreenMail mailServer = new GreenMail(setup);
    JavaMailSenderImpl jmsi = (JavaMailSenderImpl) mailSender;
    mailServer.setUser(jmsi.getUsername(), jmsi.getPassword());
    mailServer.start();
    jmsi.setPort(smtpPort);
    sshCallShell((is, os) -> {
        write(os, "health info");
        verifyResponseContains(is, "{\r\n  \"status\" : \"UP\"");
        mailServer.stop();
    });
}
 
Example #3
Source File: EmailNotificationTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Before
public void before() {
    EmailSmtpConfig smtpCfg = new EmailSmtpConfig();
    smtpCfg.setPort(3025);
    smtpCfg.setLogin(user);
    smtpCfg.setPassword(user);

    EmailConfig eCfg = new EmailConfig();
    eCfg.setConnector(EmailSmtpConnector.ID);
    eCfg.getIdentity().setFrom(sender);
    eCfg.getIdentity().setName(senderName);
    eCfg.getConnectors().put(EmailSmtpConnector.ID, GsonUtil.makeObj(smtpCfg));

    MxisdConfig cfg = new MxisdConfig();
    cfg.getMatrix().setDomain(domain);
    cfg.getKey().setPath(":memory:");
    cfg.getStorage().getProvider().getSqlite().setDatabase(":memory:");
    cfg.getThreepid().getMedium().put(ThreePidMedium.Email.getId(), GsonUtil.makeObj(eCfg));

    m = new Mxisd(cfg);
    m.start();

    gm = new GreenMail(ServerSetupTest.SMTP_IMAP);
    gm.start();
}
 
Example #4
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 #5
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 #6
Source File: TestEmailNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ServerSetup serverSetup = new ServerSetup(getFreePort(), "localhost", "smtp");
  server = new GreenMail(serverSetup);
  server.setUser("user@x", "user", "password");
  server.start();

  Configuration conf = new Configuration();
  conf.set("mail.smtp.host", "localhost");
  conf.set("mail.smtp.port", Integer.toString(server.getSmtp().getPort()));
  emailSender = new EmailSender(conf);

  runtimeInfo = new StandaloneRuntimeInfo(
      RuntimeInfo.SDC_PRODUCT,
      RuntimeModule.SDC_PROPERTY_PREFIX,
      new MetricRegistry(),
      Arrays.asList(TestEmailNotifier.class.getClassLoader())
  );
}
 
Example #7
Source File: ConcurrentCloseIT.java    From greenmail with Apache License 2.0 6 votes vote down vote up
private void testThis() throws InterruptedException {
    final GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP);
    greenMail.setUser("test@localhost", "test@localhost");
    greenMail.start();
    final SenderThread sendThread = new SenderThread();
    try {
        sendThread.start();
        greenMail.waitForIncomingEmail(3000, 1);
        final MimeMessage[] emails = greenMail.getReceivedMessages();
        assertEquals(1, emails.length);
        sendThread.join(10000);
    } finally {
        greenMail.stop();
    }

    if (sendThread.exc != null) {
        throw sendThread.exc;
    }
}
 
Example #8
Source File: ServerStartStopTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartStop() {
    GreenMail service = new GreenMail(ServerSetupTest.ALL);
    try {
        // Try to stop before start: Nothing happens
        service.stop();
        service.start();
        service.stop();
        // Now the server is stopped, should be started by reset command
        service.reset();
        // Start again
        service.reset();
    } finally {
        // And finally stop
        service.stop();
    }
}
 
Example #9
Source File: DefaultEmailServiceContextBasedTest.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(templateService.mergeTemplateIntoString(anyString(), any(Map.class)))
            .thenReturn("<!doctype html>\n" +
                    "<html>\n" +
                    "<body>\n" +
                    "<p>\n" +
                    "    THIS IS A TEST WITH TEMPLATE\n" +
                    "</p>\n" +
                    "</body>\n" +
                    "</html>");

    ServerSetup serverSetup = new ServerSetup(MAIL_PORT, (String) null, "smtp");
    testSmtp = new GreenMail(serverSetup);
    testSmtp.start();

    //don't forget to set the test port!
    ((JavaMailSenderImpl) javaMailSender).setPort(serverSetup.getPort());
    ((JavaMailSenderImpl) javaMailSender).setHost("localhost");
}
 
Example #10
Source File: ExampleReceiveNoRuleTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceive() throws MessagingException, IOException {
    //Start all email servers using non-default ports.
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.start();

        //Use random content to avoid potential residual lingering problems
        final String subject = GreenMailUtil.random();
        final String body = GreenMailUtil.random();
        MimeMessage message = createMimeMessage(subject, body, greenMail); // Construct message
        GreenMailUser user = greenMail.setUser("[email protected]", "waelc", "soooosecret");
        user.deliver(message);
        assertEquals(1, greenMail.getReceivedMessages().length);

        // --- Place your retrieve code here

    } finally {
        greenMail.stop();
    }
}
 
Example #11
Source File: SmtpOutputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception
{
  node = new SmtpOutputOperator();
  greenMail = new GreenMail(ServerSetupTest.ALL);
  greenMail.start();
  node.setFrom(from);
  node.setContent(content);
  node.setSmtpHost("127.0.0.1");
  node.setSmtpPort(ServerSetupTest.getPortOffset() + ServerSetup.SMTP.getPort());
  node.setSmtpUserName(from);
  node.setSmtpPassword("<password>");
  //node.setUseSsl(true);
  node.setSubject(subject);
  data = new HashMap<String, String>();
  data.put("alertkey", "alertvalue");

}
 
Example #12
Source File: GreenMailServer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server and add the user.
 */
public static void startServer() {
    greenMail = new GreenMail();
    greenMail.start();
    primaryUser = greenMail.setUser(USER_EMAIL, USER_LOGIN, USER_PW);
    log.info("GreenMail Server started and user added!");
}
 
Example #13
Source File: GreenMailServiceImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    GreenMail greenMail = (GreenMail) messageContext.getServletContext().
            getAttribute(GreenMailStartStopListener.GREENMAIL);
    if (greenMail != null) {
        ((InterruptableSmtpServer) greenMail.getSmtp()).setRejectRequests(false);
        LOG.info("SMTP server is accepting requests");
    }
}
 
Example #14
Source File: GreenMailServiceImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    GreenMail greenMail = (GreenMail) messageContext.getServletContext().
            getAttribute(GreenMailStartStopListener.GREENMAIL);
    if (greenMail != null) {
        ((InterruptableSmtpServer) greenMail.getSmtp()).setRejectRequests(true);
        LOG.info("SMTP server is rejecting requests");
    }
}
 
Example #15
Source File: MailPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    GreenMail greenMail = new GreenMail(); // uses test ports by default
    greenMail.start();
    try {
        transactionMarker();
    } finally {
        greenMail.stop();
    }
}
 
Example #16
Source File: ExampleSendNoRuleAdvTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSend() throws MessagingException, IOException {
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.start();

        //Use random content to avoid potential residual lingering problems
        final String subject = GreenMailUtil.random();
        final String body = GreenMailUtil.random();

        sendTestMails(subject, body); // Place your sending code here

        //wait for max 5s for 1 email to arrive
        //waitForIncomingEmail() is useful if you're sending stuff asynchronously in a separate thread
        assertTrue(greenMail.waitForIncomingEmail(5000, 2));

        //Retrieve using GreenMail API
        Message[] messages = greenMail.getReceivedMessages();
        assertEquals(2, messages.length);

        // Simple message
        assertEquals(subject, messages[0].getSubject());
        assertEquals(body, GreenMailUtil.getBody(messages[0]).trim());

        //if you send content as a 2 part multipart...
        assertTrue(messages[1].getContent() instanceof MimeMultipart);
        MimeMultipart mp = (MimeMultipart) messages[1].getContent();
        assertEquals(2, mp.getCount());
        assertEquals("body1", GreenMailUtil.getBody(mp.getBodyPart(0)).trim());
        assertEquals("body2", GreenMailUtil.getBody(mp.getBodyPart(1)).trim());
    } finally {
        greenMail.stop();
    }
}
 
Example #17
Source File: ExampleSendNoRuleSimpleTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSend() throws MessagingException {
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP); //uses test ports by default
    try {
        greenMail.start();
        GreenMailUtil.sendTextEmailTest("[email protected]", "[email protected]", "some subject",
                "some body"); //replace this with your test message content
        assertEquals("some body", GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]));
    } finally {
        greenMail.stop();
    }
}
 
Example #18
Source File: GreenMailConfigurationTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsersAccessible() {
    GreenMail greenMail = new GreenMail(ServerSetupTest.IMAP).withConfiguration(
            testUsersAccessibleConfig()
    );
    greenMail.start();
    try {
        GreenMailConfigurationTestBase.testUsersAccessible(greenMail);
    } finally {
        greenMail.stop();
    }
}
 
Example #19
Source File: GreenMailUtilTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendTextEmailTest() throws Exception {
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.setUser("foo@localhost", "pwd");
        greenMail.start();
        GreenMailUtil.sendTextEmail("\"Foo, Bar\" <foo@localhost>", "\"Bar, Foo\" <bar@localhost>",
                "Test subject", "Test message", ServerSetupTest.SMTP);
        greenMail.waitForIncomingEmail(1);

        Store store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            assertTrue(null != msgs && msgs.length == 1);
            Message m = msgs[0];
            assertEquals("Test subject", m.getSubject());
            Address[] a = m.getRecipients(Message.RecipientType.TO);
            assertTrue(null != a && a.length == 1
                    && a[0].toString().equals("\"Foo, Bar\" <foo@localhost>"));
            a = m.getFrom();
            assertTrue(null != a && a.length == 1
                    && a[0].toString().equals("\"Bar, Foo\" <bar@localhost>"));
            assertTrue(m.getContentType().toLowerCase()
                    .startsWith("text/plain"));
            assertEquals("Test message", m.getContent());
        } finally {
            store.close();
        }
    } finally {
        greenMail.stop();
    }
}
 
Example #20
Source File: GreenMailUtilTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAndGetQuota() throws MessagingException {
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.start();

        final GreenMailUser user = greenMail.setUser("foo@localhost", "pwd");

        Store store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");

        Quota testQuota = new Quota("INBOX");
        testQuota.setResourceLimit("STORAGE", 1024L * 42L);
        testQuota.setResourceLimit("MESSAGES", 5L);

        assertEquals(0, GreenMailUtil.getQuota(user, testQuota.quotaRoot).length);
        GreenMailUtil.setQuota(user, testQuota);

        final Quota[] quota = GreenMailUtil.getQuota(user, testQuota.quotaRoot);
        assertEquals(1, quota.length);
        assertEquals(2, quota[0].resources.length);

        store.close();
    } finally {
        greenMail.stop();
    }
}
 
Example #21
Source File: GreenMailStandaloneRunner.java    From greenmail with Apache License 2.0 5 votes vote down vote up
/**
 * Start and configure GreenMail using given properties.
 *
 * @param properties the properties such as System.getProperties()
 */
public void doRun(Properties properties) {
    ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties);

    if (serverSetup.length == 0) {
        printUsage(System.out);

    } else {
        greenMail = new GreenMail(serverSetup);
        log.info("Starting GreenMail standalone v{} using {}",
                BuildInfo.INSTANCE.getProjectVersion(), Arrays.toString(serverSetup));
        greenMail.withConfiguration(new PropertiesBasedGreenMailConfigurationBuilder().build(properties))
                .start();
    }
}
 
Example #22
Source File: GreenMailBean.java    From greenmail with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by a BeanFactory after it has set all bean properties supplied (and satisfied
 * BeanFactoryAware and ApplicationContextAware). <p>This method allows the bean instance to
 * perform initialization only possible when all bean properties have been set and to throw an
 * exception in the event of misconfiguration.
 *
 * @throws Exception in the event of misconfiguration (such as failure to set an essential
 *                   property) or if initialization fails.
 */
@Override
public void afterPropertiesSet() throws Exception {
    greenMail = new GreenMail(createServerSetup());
    if (null != users) {
        for (String user : users) {
            int posColon = user.indexOf(':');
            int posAt = user.indexOf('@');
            String login = user.substring(0, posColon);
            String pwd = user.substring(posColon + 1, posAt);
            String domain = user.substring(posAt + 1);
            if (log.isDebugEnabled()) {
                log.debug("Adding user {}:{}@{}" ,login, pwd, domain);
            }
            greenMail.setUser(login + '@' + domain, login, pwd);
        }
    }
    if (autostart) {
        greenMail.start();
        started = true;
    }
}
 
Example #23
Source File: ITestConsumeEmail.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    mockIMAP4Server = new GreenMail(ServerSetupTest.IMAP);
    mockIMAP4Server.start();
    mockPOP3Server = new GreenMail(ServerSetupTest.POP3);
    mockPOP3Server.start();

    imapUser = mockIMAP4Server.setUser("[email protected]", "nifiUserImap", "nifiPassword");
    popUser = mockPOP3Server.setUser("[email protected]", "nifiUserPop", "nifiPassword");
}
 
Example #24
Source File: GreenMailRule.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    ServerSetup setup = new ServerSetup(port, host, "smtp");

    greenMail = new GreenMail(setup);
    greenMail.start();
}
 
Example #25
Source File: MailServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void start() {
    ServerSetup setup = new ServerSetup(Integer.parseInt(PORT), HOST, "smtp");

    greenMail = new GreenMail(setup);
    greenMail.start();

    log.info("Started mail server (" + HOST + ":" + PORT + ")");
}
 
Example #26
Source File: MailServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");

    GreenMail greenMail = new GreenMail(setup);
    greenMail.start();

    System.out.println("Started mail server (localhost:3025)");
    System.out.println();
    
    while (true) {
        int c = greenMail.getReceivedMessages().length;

        if (greenMail.waitForIncomingEmail(Long.MAX_VALUE, c + 1)) {
            MimeMessage message = greenMail.getReceivedMessages()[c++];
            System.out.println("-------------------------------------------------------");
            System.out.println("Received mail to " + message.getRecipients(RecipientType.TO)[0]);
            if (message.getContent() instanceof MimeMultipart) {
                MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
                for (int i = 0; i < mimeMultipart.getCount(); i++) {
                    System.out.println("----");
                    System.out.println(mimeMultipart.getBodyPart(i).getContentType() + ":");
                    System.out.println();
                    System.out.println(mimeMultipart.getBodyPart(i).getContent());
                }
            } else {
                System.out.println();
                System.out.println(message.getContent());
            }
            System.out.println("-------------------------------------------------------");
        }
    }
}
 
Example #27
Source File: SendEmailTestCase.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Mock a smtp server.
 * @return GreenMail smtp server.
 * @throws IOException If something goes wrong.
 */
public GreenMail smtpServer(String bind, int port) throws IOException {
    return new GreenMail(
        new ServerSetup(
            port, bind,
            ServerSetup.PROTOCOL_SMTP
        )
    );
}
 
Example #28
Source File: TestConsumeEmail.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    mockIMAP4Server = new GreenMail(ServerSetupTest.IMAP);
    mockIMAP4Server.start();
    mockPOP3Server = new GreenMail(ServerSetupTest.POP3);
    mockPOP3Server.start();

    imapUser = mockIMAP4Server.setUser("[email protected]", "nifiUserImap", "nifiPassword");
    popUser = mockPOP3Server.setUser("[email protected]", "nifiUserPop", "nifiPassword");
}
 
Example #29
Source File: LifeCycleTest.java    From QuizZz with MIT License 5 votes vote down vote up
@Before
public void setup() {
	mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();

	smtpServer = new GreenMail(ServerSetupTest.SMTP);
	smtpServer.start();
}
 
Example #30
Source File: MailHelper.java    From QuizZz with MIT License 5 votes vote down vote up
public static String waitForEmailAndExtractUrl(GreenMail smtpServer) throws IOException, MessagingException {
	smtpServer.waitForIncomingEmail(1);
	Message[] messages = smtpServer.getReceivedMessages();
	smtpServer.reset();
	assertEquals(1, messages.length);

	return extractUrlFromMail(messages[0]);
}