About GreenMail
Introduction
GreenMail is an open source, intuitive and easy-to-use test suite of email servers for testing purposes.
Typical use cases include mail integration testing or lightweight sand boxed mail server for development.
- Supports SMTP, POP3 and IMAP including TLS/SSL
- Prevents accidental email leaking to real mail servers (non-forwarding / sand-boxed)
- Embeds in JUnit test for integration testing
- Provides flexible standalone run options such as
- 2.1.x stable
- Jakarta Mail 2.1.x
- Angus Mail
- Jakarta EE 10
- Java 11
- 2.0.x maintenance
- Jakarta Mail 2.0.x (jakarta.mail package prefix change)
- Jakarta EE 9
- Java 8
- 1.6.x maintenance
- Jakarta Mail 1.6.x(javax.mail package)
- Java 8
Scenarios
GreenMail is useful in the following scenarios:
Test Your Sending Code
- System testing an application. GreenMail responds like a regular SMTP server but does not deliver any email, which enables it to be used in real life applications and real test cases. Messages can easily be extracted, verified and modified. Support for SMTPS (SSL) is enabled.
- GreenMail is an excellent choice for unit testing code that needs to send email with a succinct, efficient (non-polling) way to wait for messages to arrive, retrieve, verify, and modify messages.
- Note that retrieval of emails can be made with a simple java method or through a provided POP3, IMAP retriever helper class. Alternatively you can use a local client like Thunderbird.
- The example below is using the GreenMail JUnit rule. See examples for hints on how to use GreenMail without the rule.
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP);
@Test
public void testSend() throws MessagingException {
GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost",
"some subject", "some body"); // --- Place your sending code here instead
assertEquals("some body", greenMail.getReceivedMessages()[0].getContent());
}
Test Your Retrieving Code
- Again GreenMail can be used for system or unit testing an application needing to use POP3 or IMAP by responding like a standard compliant POP3 or IMAP server. Support for POP3S and IMAPS (SSL) is also enabled.
- Messages can be placed directly in users mailboxes, by using SMTP or preloaded from file system.
- GreenMail ships with helper classes for sending and retrieving. See the javadocs for the Retriever.java class
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP_IMAP);
@Test
public void testReceive() throws MessagingException {
GreenMailUser user = greenMail.setUser("to@localhost", "login-id", "password");
user.deliver(createMimeMessage()); // You can either create a more complex message...
GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost",
"subject", "body"); // ...or use the default messages
assertEquals(2, greenMail.getReceivedMessages().length); // // --- Place your POP3 or IMAP retrieve code here
}
Sending and Retrieving
GreenMail can easily be configured to use all or a combination of ports, protocols, and bind addresses. For example, it's possible to run GreenMail on SMTP, POP3, POP3S and IMAPS ports as easily as only SMTP. Many systems might already be running these servers or don't allow non-root users to open the default ports which is why GreenMail ships with a special configuration for testing.
Mocking a mail server for your development environment
GreenMail provides a JBoss GreenMail service for mocking a mail server for development. It saves you the overhead of either installing a full productive server (like Apache James).
Check out the possible deployments as webapp, standalone or standalone docker image.
Implementation
The implementation is in 100% Java with only a few library dependencies for GreenMail Core:
- Jakarta Mail
- Java Activation Framework
- SLF4J Simple Logging Facade for Java for logging
- Junit - required for easy test setup using Rules
GreenMail contains several modules:
- com.icegreen:greenmail-core - Core library for unit tests
- com.icegreen:greenmail-standalone - Standalone runner (e.g. when not using GreenMail embedded into unit test)
- com.icegreen:greenmail-docker-standalone - Dockerized standalone runner
- com.icegreen:greenmail-junit4 - JUnit4 support via GreenMailRule
- com.icegreen:greenmail-junit5 - JUnit5 support via GreenMailExtension
- com.icegreen:greenmail-webapp
- com.icegreen:greenmail-spring - Spring framework support via GreenMailBean
Source Code
You find the source on GitHub including build instructions. GreenMail is open source released under The Apache 2.0 License.
GreenMail's protocol source code is based on a cocktail of Foedus and James.
Links
The following lists provide helpful links related to GreenMail and email integration testing.
Projects extending/wrapping GreenMail:
- Example container integrations of GreenMail and various web based mail clients
- Citrus Integration Testing used GreenMail for mocking mail server
- Spring Integration 5.5 uses now GreenMail for email integration testing
- GreenMail HTTP encapsulates GreenMail Standalone, adds a web server to deliver JSON and web pages showing the internals of GreenMail
- Grails Plugin for GreenMail including REST-like GreenMail control interface and UI
- Play Plugin for GreenMail including REST-like control interface and UI
- JCA Adapter for GreenMail
- Deprecated SourceForge GreenMail project location before migration to GitHub in 2014
Articles&Blogs:
- Manually testing email notifications with GreenMail mock mail server
- "Testing email with GreenMail, a mock mail server" @ OpenValue Meetup
- Use GreenMail For Spring Mail (JavaMailSender) JUnit 5 Integration Tests
- Spring Boot Admin and GreenMail
- Deploy local email server mock for testing with GreenMail
- Catch-all SMTP servers for development and testing
- Using GreenMail to enhance JHipster integration tests
- Using dynamic ports in spring boot integration tests
- Integration Testing IMAP, SMTP and POP3 with GreenMail
- Unit testing Java mail code
Projects using GreenMail include:
- Spring Integration 5.5 uses now GreenMail
- Alfresco
- Salesforce MuleSoft
- ... and many more. Tell us about your project :-)
Related projects to JavaMail and testing/development:
- Wiser alias Subethasmtp,
- Apache James, a full-blown enterprise mail server
- DevNullSmtp
- JavaMail Mock2
- Collection of IMAP related RFCs
Thanks
Special thanks to all contributors for feedback and patches!
Many thanks to and JetBrains for supporting this project with free OSS licenses!
Examples
Using JUnit4 rule based setup
The rule GreenMailRule provided by com.icegreen:greenmail-junit4 will take care of starting and stopping GreenMail for each test, providing a clean environment.
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleRuleTest.java) */
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP);
@Test
public void testSomething() {
GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost", "subject", "body");
MimeMessage[] emails = greenMail.getReceivedMessages();
assertEquals(1, emails.length);
assertEquals("subject", emails[0].getSubject());
assertEquals("body", emails[0].getContent());
// ...
}
Using JUnit5 extension
The JUnit5 GreenMailExtension included in com.icegreen:greenmail-junit5 replaces JUnit 4 rule GreenMailRule and also take care of starting and stopping GreenMail as part of the test lifecycle.
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-junit5/src/test/java/com/icegreen/greenmail/junit5/CustomSetupTests.java) */
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP);
@Test
@DisplayName("Send test")
void testSend() {
GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost", "some subject", "some body");
final MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
final MimeMessage receivedMessage = receivedMessages[0];
assertEquals("some body", receivedMessage.getContent());
}
Testing your sending code (simple)
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleSendTest.java) */
GreenMail greenMail = new GreenMail(); //uses test ports by default
greenMail.start();
GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost", "some subject",
"some body"); // --- Place your sending code here
assertEquals("some body", greenMail.getReceivedMessages()[0].getContent());
greenMail.stop();
Testing your sending code (detecting available port)
This example starts an SMTP server trying to find an available, unused port and helps when colliding with Windows 'reserved' port ranges or if multiple tests run in parallel:
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleSendTest.java) */
GreenMail greenMailWithDynamicPort = new GreenMail(ServerSetupTest.SMTP.dynamicPort()); // Try to find available port
greenMailWithDynamicPort.start();
try {
GreenMailUtil.sendTextEmail(
"to@localhost", "from@localhost", "some subject", "Sent using available port detection",
greenMailWithDynamicPort.getSmtp().getServerSetup()); // Important: Pass dynamic port setup here
assertEquals("Sent using available port detection", greenMailWithDynamicPort.getReceivedMessages()[0].getContent());
assertNotEquals("Dynamic port must differ", ServerSetupTest.SMTP.getPort(), greenMailWithDynamicPort.getSmtp().getPort());
} finally {
greenMailWithDynamicPort.stop();
}
Testing your sending code (advanced)
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleSendNoRuleAdvTest.java) */
GreenMail greenMail = new GreenMail(ServerSetupTest.ALL);
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, messages[0].getContent());
//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", mp.getBodyPart(0).getContent());
assertEquals("body2", mp.getBodyPart(1).getContent());
greenMail.stop();
Testing your retrieving code
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleReceiveTest.java) */
//Start all email servers using non-default ports.
GreenMail greenMail = new GreenMail(ServerSetupTest.ALL);
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("wael@localhost", "waelc", "soooosecret");
user.deliver(message);
assertEquals(1, greenMail.getReceivedMessages().length);
// --- Place your retrieve code here
greenMail.stop();
Testing using plain JavaMail for sending/retrieving code
/** [See code on GitHub](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-core/src/test/java/com/icegreen/greenmail/examples/ExampleJavaMailTest.java) */
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.SMTP_IMAP);
@Test
public void testSendAndReceive() throws MessagingException, ... {
Session smtpSession = greenMail.getSmtp().createSession();
Message msg = new MimeMessage(smtpSession);
msg.setFrom(new InternetAddress("foo@example.com"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("bar@example.com"));
msg.setSubject("Email sent to GreenMail via plain JavaMail");
msg.setText("Fetch me via IMAP");
Transport.send(msg);
// Create user, as connect verifies pwd
greenMail.setUser("bar@example.com", "bar@example.com", "secret-pwd");
// Alternative 1: Create session and store or ...
Session imapSession = greenMail.getImap().createSession();
Store store = imapSession.getStore("imap");
store.connect("bar@example.com", "secret-pwd");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msgReceived = inbox.getMessage(1);
assertEquals(msg.getSubject(), msgReceived.getSubject());
...
// Alternative 2: ... let GreenMail create and configure a store:
IMAPStore imapStore = greenMail.getImap().createStore();
imapStore.connect("bar@example.com", "secret-pwd");
inbox = imapStore.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
msgReceived = inbox.getMessage(1);
...
// Alternative 3: ... directly fetch sent message using GreenMail API
assertEquals(1, greenMail.getReceivedMessagesForDomain("bar@example.com").length);
msgReceived = greenMail.getReceivedMessagesForDomain("bar@example.com")[0];
...
}
Testing using Spring framework
The com.icegreen:greenmail-spring module provides basic support for Spring configuration via GreenMailBean:
/** See [GreenMailBeanTest.java](https://github.com/greenmail-mail-test/greenmail/tree/master/greenmail-spring/src/test/java/com/icegreen/greenmail/spring/GreenMailBeanTest.java)
* and [GreenMailBeanTest-context.xml](greenmail-spring/src/test/resources/com/icegreen/greenmail/spring/GreenMailBeanTest-context.xml)
*/
@Autowired
private GreenMailBean greenMailBean;
@Test
public void testCreate() {
GreenMail greenMail = greenMailBean.getGreenMail();
...
}
Deployment
Run GreenMail as standalone java application
Running GreenMail as a standalone process is useful if you want a simple sand boxed mail server.
All you require is a compatible JRE and the standalone JAR. The standalone JAR already contains all dependencies and a default logging.
You can configure GreenMail by setting system properties, and activate a minimal RESTful API (requires GreenMail 1.6.2+) for e.g. adding users, purging mails or resetting GreenMail instance.
Starting GreenMail standalone
java [OPTIONS] -jar greenmail-standalone.jar
Option | Description |
-Dgreenmail.setup.all | Uses ServerSetup.ALL
configuration to start all default mail services using default ports:
-Dgreenmail.setup.all
|
-Dgreenmail.setup.test.all | Uses ServerSetupTest.ALL
configuration to start all default mail services using default ports including offset of
3000:
-Dgreenmail.setup.test.all
|
-Dgreenmail.PROTOCOL.hostname | Configures the hostname (or IP bind address) and activates a server for given protocol.
Protocol can be one of
-Dgreenmail.smtp.hostname=127.0.0.1 -Dgreenmail.smtp.port=3025
Note: Requires -Dgreenmail.PROTOCOL.port option! Exception is api with default port 8080.
|
-Dgreenmail.PROTOCOL.port | Configures the port for given protocol.
Use 0 for dynamically finding an available port. Protocol can be one of
-Dgreenmail.smtp.port=3025 -Dgreenmail.smtp.hostname=127.0.0.1
Note: Requires -Dgreenmail.PROTOCOL.hostname option! Exception is api with default port 8080.
|
-Dgreenmail.hostname | Configures the default hostname or ip bind address.
Note: Hostnames must be DNS resolvable!
Note: Default hostname is 127.0.0.1
-Dgreenmail.smtp.port=3025 -Dgreenmail.imap.port=3143 -Dgreenmail.hostname=0.0.0.0
|
-Dgreenmail.users=user1[, ..., userN] | Configures the user mail boxes including password.
The list of users is comma separated. A single user is of format local-part:password[@domain] , where the domain part is optional.
-Dgreenmail.users=foo:pwd@bar.com,jabber:wocky@monster.local,foo1:bar
|
-Dgreenmail.users.login=(local_part|email) Requires 1.6.1 |
Configures if local_part (default) or full email should be used for login when configuring users via -Dgreenmail.users=foo@bar.com,....
Note: Only has effect if configured user is of type email (i.e. contains '@')
-Dgreenmail.users.login=email
|
-Dgreenmail.tls.keystore.file Requires 1.6.8/2.0.0 |
Configures a PKCS12 keystore for secure IMAP/SMTP/POP3 TLS certificates (see also -Dgreenmail.tls.keystore.password)
Example and default used in GreenMail container image:
-Dgreenmail.tls.keystore.file=/home/greenmail/greenmail.p12
|
-Dgreenmail.tls.keystore.password Requires 1.6.8/2.0.0 |
Configures a PKCS12 keystore password (see also -Dgreenmail.tls.keystore.file)
Example and default used in GreenMail container image:
-Dgreenmail.tls.keystore.password=changeit
|
-Dgreenmail.tls.key.password Requires 1.6.15/2.0.1/2.1.0-alpha-3 |
Configures a PKCS12 key password. Defaults to keystore password.
Example and default used in GreenMail container image:
-Dgreenmail.tls.key.password=changeit4key
|
-Dgreenmail.auth.disabled | Disables user authentication check, so that any password works.
Useful if you do not want to preconfigure user/passwords.
GreenMail automatically creates non-existent users.
Example:
-Dgreenmail.auth.disabled
|
-Dgreenmail.verbose | Enables verbose mode.
Useful if you want to see debug and protocol level output.
Example:
-Dgreenmail.verbose
|
-Dgreenmail.sieve.ignore.detail Requires 2.1.0-alpha-2 |
Disables RFC5233 sub addressing handling.
Use this flag if you want to avoid removing sub adress detail from email.
Example:
-Dgreenmail.sieve.ignore.detail (would not strip sub address detail part '+bar' from email 'foo+bar@localhost')
|
-Dgreenmail.startup.timeout | Overrides the default server startup timeout of 1000ms.
Useful if you have a slow or overloaded environment.
Example with 2s startup timeout:
-Dgreenmail.startup.timeout=2000
|
-Dgreenmail.preload.dir Requires 1.6.15/2.0.1/2.1.0-alpha-3 |
Preloads mails (including users) from filesystem
Example:
-Dgreenmail.preload.dir=/tmp/preload-example
tmp └──preload-example ├── bar@localhost # Creates user (login and credentials default to email) │ └── INBOX │ └── test-5.eml # Loads email ├── drafts@localhost │ └── Drafts # Creates folder ├── foo-bar@localhost └── foo@localhost ├── Drafts │ └── draft.eml └── INBOX ├── f1 │ ├── f2 │ │ ├── test-3.eml │ │ └── test-4.eml │ └── test-2.eml └── test-1.eml |
-Dlog4j.configuration | Configures log4j using given configuration file. By default, GreenMail standalone runner uses a provided log4j configuration packed into the standalone ueber JAR. This options allows you to override the default log4j configuration by providing your own log4j configuration file.
Example:
-Dlog4j.configuration=file:///tmp/log4j.xml
|
GreenMail standalone examples
Test setup for SMTP/IMAP and one user
Starts GreenMail for SMTP (test port 3025) and IMAP (test port 3143) using localhost/127.0.0.1 and a single user test1 with password pwd1 and email test1@localhost :
java -Dgreenmail.setup.test.smtp -Dgreenmail.setup.test.imap \
-Dgreenmail.users=test1:pwd1 -jar greenmail-standalone.jar
Test setup for SMTP(S)/IMAP(S)/POP3(S) and two user
Starts GreenMail for SMTP (test port 3025), SMTPS (test port 3465), IMAP (test port 3143), IMAPS (test port 3993), POP3 (test port 3110) and POP3S (test port 3995) using localhost/127.0.0.1 :
java -Dgreenmail.setup.test.all -Dgreenmail.users=test1:pwd1,test2:pwd2@example.com \
-jar greenmail-standalone.jar
Test setup for SMTP(S)/IMAP(S)/POP3(S), one user and bound to 0.0.0.0
Starts GreenMail for SMTP (test port 3025), SMTPS (test port 3465), IMAP (test port 3143), IMAPS (test port 3993), POP3 (test port 3110), POP3S (test port 3995) and API (port 8080) using 0.0.0.0 :
java -Dgreenmail.setup.test.all -Dgreenmail.users=test1:pwd1 \
-Dgreenmail.hostname=0.0.0.0 \
-jar greenmail-standalone.jar
SMTP only
Starts GreenMail with directly configured SMTP on 127.0.0.1:4025
java -Dgreenmail.smtp.hostname=127.0.0.1 -Dgreenmail.smtp.port=4025 \
-jar greenmail-standalone.jar
Deploy as a standalone Docker image
GreenMail provides a pre-configured Docker image running GreenMail standalone. The image is available via Docker Hub Public Repository, but you can also build it yourself using our Dockerfile.
By default, GreenMail standalone runs as user greenmail using the GreenMail test setup with the following default settings and exposed ports.
Docker Environment ENV variable | Description | Default |
---|---|---|
GREENMAIL_OPTS | GreenMail standalone options | -Dgreenmail.setup.test.all -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.auth.disabled |
JAVA_OPTS | Generic JVM options | -Djava.net.preferIPv4Stack=true |
Port | Description |
---|---|
3025 | SMTP |
3110 | POP3 |
3143 | IMAP |
3465 | SMTPS |
3993 | IMAPS |
3995 | POP3S |
8080 | API |
Using docker to run the image
docker pull greenmail/standalone:2.0.1
docker run -t -i -p 3025:3025 -p 3110:3110 -p 3143:3143 \
-p 3465:3465 -p 3993:3993 -p 3995:3995 -p 8080:8080 \
greenmail/standalone:2.0.1
If you want to test it, you can do a quick check with telnet (or any other mail program) by connecting to the exposed SMTP port and checking if GreenMail SMTP server responds:
Passing configuration options to GreenMail Standalone Docker image
You can also configure the JVM and GreenMail configuration options via the Docker environment variables JAVA_OPTS and GREENMAIL_OPTS:
docker run -t -i \
-e GREENMAIL_OPTS='-Dgreenmail.setup.test.all -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.auth.disabled -Dgreenmail.verbose' \
-e JAVA_OPTS='-Djava.net.preferIPv4Stack=true -Xmx512m' \
-p 3025:3025 -p 3110:3110 -p 3143:3143 \
-p 3465:3465 -p 3993:3993 -p 3995:3995 -p 8080:8080 \
greenmail/standalone:2.0.1
Deploy as a webapp (WAR)
GreenMail Webapp provides a lightweight Java web application wrapping GreenMail mail server and exposing GreenMail API.
The usage scenario is a development or test environment where a real mail server is too much overhead. The webapp is application server neutral - you should be able to use it on any Java EE 7 application server (Servlet 3.1) running and Java 8 (or greater).
With the GreenMail mail service each developer has its own local mail server sandbox - so there's no danger for accidentally leaking test mails into the Internet.
Deploy the webapp
Simply deploy the webapp like any other Java web application.
For Tomcat, just drop the webapp into $CATALINA_HOME/webapps directory. Alternatively, you can create a $CATALINA_HOME/webapps/greenmail, unpack the WAR here and configure the GreenMail service.
Configure the webapp
You can configure the active mail services and available users by editing WEB-INF/web.xml in the WAR file and modifying the context params. A ServletContextListener starts and stops the GreenMail service when deploying/un-deploying.
Name | Description |
greenmail.defaultHostname | The mail server default hostname (defaults to localhost). |
greenmail.portOffset | Offset added to the standard mail ports. Default is 10000 (so an activated SMTP service would start up on port 10025). |
greenmail.<PROTOCOL> | Starts a server for this mail protocol (using defaultHostname, port offset and default
port).
Available protocol names include
|
greenmail.<PROTOCOL>.host | Optionally overwrites the default host name (localhost). |
greenmail.<PROTOCOL>.port | Optionally overwrites the default port and port offset for the given protocol. |
greenmail.users | A whitespace/newline/comma separated list of mail users in the form of USER:PWD@DOMAIN. |
Have a look at the default web.xml.
Features
API
GreenMail provides a RESTful API focusing on administrative tasks like purging mails or adding users.
Operations include
- Getting currently configured user and adding new users
- Getting current configuration (e.g. which service like SMTP runs on which port)
- Purging all mailboxes of emails
- Resetting GreenMail to original configuration (restarts server, purges all mails and users added via API)
- Getting mail messages for a user and optional folder (simplified, containing message uid/subject/raw mime message as recommended usage is via e.g. IMAP)
The OpenAPI rendered UI can be used for invoking the API, e.g. for adding a new user:
Preloading emails from filesysem
You can preload user/folder/emails from filesystem
Delivery Status Notification (DSN)
You can provide custom DSN behavior by implementing MessageDeliveryHandler.java. See ExampleUndeliverableTest.java
FAQ
How come I don't have to create any accounts to send/retrieve?
By default, GreenMail accepts all incoming emails. If there is no corresponding existing email account, one is automatically created with login and password being the same as the to-address.
What other library dependencies are there?
Check out the Maven POM. Dependencies include
- javamail.jar and activation.jar
- slf4j-api.jar (for logging)
- junit.jar (for test rules)
How come I don't need to install any SSL/TLS related certificates?
GreenMail is designed to be used out of the box with no need to generate, sign or install any certificates into your keystore. GreenMail ships with a builtin keystore with a self-signed RSA key. Refer to the source code of DummySSLServerSocketFactory for details.
How can I replace the included default certificate?
You can use the system properties -Dgreenmail.tls.keystore.file
and -Dgreenmail.tls.keystore.password
for pointing to your own PKCS12 file and password, if you do not want to use the provided default one (included in GreenMail JAR).
How can I use IMAP quotas?
GreenMail supports IMAP quota. Quota capability can be toggled on and off. For details see ImapServerTest.java quota test
How can I create or delete a mail user?
GreenMail greenMail = ...
// Create user with login id equals email
GreenMailUser user1 = greenMail.setUser("foo@localhost", "some secret pwd");
// Create user with login id different than email
GreenMailUser user2 = greenMail.setUser("foo@localhost", "login-id", "some secret pwd");
...
greenMail.getManagers().getUserManager().deleteUser(user1); // Delete user
How can I get more verbose output?
Enable the verbose mode, which prints debug output and protocol level communication.
See
ServerSetup.setVerbose(boolean)
or GreenMail standalone runner option greenmail.verbose option.
Example of activating verbose mode when configuring via GreenMailRule:
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetup.verbose(ServerSetupTest.SMTP_IMAP));
How can I let GreenMail dynamically choose available port?
Set the port to 0 or use ServerSetup.SMTP.dynamicPort()
, and GreenMail will try to find an available port.
@Rule
public final GreenMailRule greenMail = new GreenMailRule(ServerSetup.SMTP.dynamicPort());
GreenMailUtil.sendTextEmail("to@localhost", "from@localhost", "subject", "body",
greenMail.getSmtp().getServerSetup());
How can I preload an existing (eml) message?
You can load an existing electronic mail (eml) message and store the message for a user in a mailbox folder.
Example: ExamplePreloadMailFromFsTest.java
How can I use nested test classes (with @Nested)?
When specifying .withPerMethodLifecycle(false)
, greenmail will initialize as "before all" for every test class. When using nested test classes this leads to an initialization in the main test class and in every nested test class. This in turn leads to the following error: "Address already in use: bind".
To circumvent that you need to override the before all behaviour and suppress the initialization in nested test classes.
public class NestedTest {
@RegisterExtension
protected static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP) {
@Override
public void beforeAll(ExtensionContext context) {
if (context.getTestClass().isPresent()) {
Class> currentClass = context.getTestClass().get();
if (!ModifierSupport.isStatic(currentClass) && currentClass.isMemberClass()) {
return;
}
}
super.beforeAll(context);
}
}
.withConfiguration(
GreenMailConfiguration.aConfig().withUser("user", "pw"))
.withPerMethodLifecycle(false);
@Nested
class NestedTestClass {
@Test
public void testA() {
// test something
}
}
}
How can I configure mail session properties?
You can configure per protocol specific mail session properties:
GreenMail greenMail = new GreenMail(new ServerSetup[]{
ServerSetupTest.SMTP,
ServerSetupTest.IMAP.mailSessionProperty("mail.imap.minidletime", "100")
});
Session session = greenMail.getImap().createSession(); // Will have configured property set
How can I direcly (avoiding IMAP/POP3) search received messages in my tests?
GreenMail provides direct access to internal user mailboxes and received messages:
// All messages received for emails ending with "localhost" and subject containing "match"
final List messages = greenMail.findReceivedMessages(
u -> u.getEmail().toLowerCase().endsWith("localhost") /* Predicate for user account, selecting users by email ending with 'localhost' */,
m -> MimeMessageHelper.getSubject(m, "").contains("match") /* Predicate for messages, selecting messages with subject attribute containing "match"*/
).collect(Collectors.toList());
Requires 2.1.0+
Download
Maven Central contains all GreenMail artifacts.
Docker images are available on Docker Hub GreenMail Repository, such as for the GreenMail standalone runner.
Quick-links
- GreenMail 2.1.x downloads (for Jakarta Mail 2.1)
- GreenMail 2.0.x downloads (for Jakarta Mail 2.0)
- GreenMail 1.6.x downloads (for Jakarta Mail 1.6)
Please note that the downloads are sorted by version and not by release date. GitHub releases page shows the releases cronological sorted.
2.1.1 - November 17th, 2024
This version requires JDK 1.8 (JDK 11) and Jakarta Mail 2.1 .
Please note that- Jakarta Mail 2.x brings breaking changes due to renamed package prefix of jakarta.mail!
- Jakarta Mail 2.1 / Angus Mail is the new reference implementation
- GreenMail standalone/webapp require Java 11 for running
Name | GAV |
GreenMail Core | com.icegreen:greenmail:2.1.1 |
GreenMail Standalone | com.icegreen:greenmail-standalone:2.1.1 (Docker Hub) |
GreenMail Webapp | com.icegreen:greenmail-webapp:2.1.1:war |
GreenMail Spring | com.icegreen:greenmail-spring:2.1.1 |
Available via Maven repository or as a ZIP from GitHub.
2.0.1 - Nov 17th, 2023
This version requires JDK 1.8+ and Jakarta Mail 2.0 .
Please note that Jakarta Mail 2.x brings breaking changes due to renamed package prefix of jakarta.mail!
Name | GAV |
GreenMail Core | com.icegreen:greenmail:2.0.1 |
GreenMail Standalone | com.icegreen:greenmail-standalone:2.0.1 (Docker Hub) |
GreenMail Webapp | com.icegreen:greenmail-webapp:2.0.1:war |
GreenMail Spring | com.icegreen:greenmail-spring:2.0.1 |
Available via Maven repository or as a ZIP from GitHub.
1.6.15 - December 3rd, 2023
This version requires JDK 1.8+ and Jakarta Mail 1.6+ .
Name | GAV |
GreenMail Core | com.icegreen:greenmail:1.6.15 |
GreenMail Standalone | com.icegreen:greenmail-standalone:1.6.15 (Docker Hub) |
GreenMail Webapp | com.icegreen:greenmail-webapp:1.6.15:war |
GreenMail Spring | com.icegreen:greenmail-spring:1.6.15 |
Available via Maven repository or as a ZIP from GitHub.
1.5.14 - July 4th, 2020
This version requires JDK 1.8+ and JavaMail 1.5+ .
Name | GAV |
GreenMail Core | com.icegreen:greenmail:1.5.14 |
GreenMail Standalone | com.icegreen:greenmail-standalone:1.5.14 (Docker Hub) |
GreenMail Webapp | com.icegreen:greenmail-webapp:1.5.14:war |
GreenMail JBoss Service | com.icegreen:greenmail-jboss-service:1.5.14:jboss-sar |
GreenMail Spring | com.icegreen:greenmail-spring:1.5.14 |
Available via Maven repository or as a ZIP from GitHub.
1.5.11 - Oct 22, 2019
This version requires JDK 1.7+ and JavaMail 1.5+ .
Name | GAV |
GreenMail Core | com.icegreen:greenmail:1.5.11 |
GreenMail Standalone | com.icegreen:greenmail-standalone:1.5.11 (Docker Hub) |
GreenMail Webapp | com.icegreen:greenmail-webapp:1.5.11:war |
GreenMail JBoss Service | com.icegreen:greenmail-jboss-service:1.5.11:jboss-sar |
GreenMail Spring | com.icegreen:greenmail-spring:1.5.11 |
Available via Maven repository or as a ZIP from GitHub.
1.4.1 - April 27th, 2015
Name | GAV |
GreenMail Core | com.icegreen:greenmail:1.4.1 |
GreenMail Webapp | com.icegreen:greenmail-webapp:1.4.1:war |
GreenMail JBoss Service | com.icegreen:greenmail-jboss-service:1.4.1:jboss-sar |
GreenMail Spring | com.icegreen:greenmail-spring:1.4.1 |
Download bundle as ZIP from GitHub.
1.3.1b - June 14th 2009
Name | GAV |
GreenMail Core | com.icegreen:greenmail:1.3.1b |
GreenMail JBoss Service | com.icegreen:greenmail-jboss-service:1.3.1b:jboss-sar |
Older versions
You can find older version at the old SourceForge download section