### Simple Manual GreenMail Testing Setup Source: https://greenmail-mail-test.github.io/greenmail/index A basic example of manually starting and stopping a GreenMail server for testing purposes. This method is suitable for simpler test cases or when integration with JUnit rules/extensions is not desired. It uses default test ports. ```java /** See code on GitHub */ 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(); ``` -------------------------------- ### Start GreenMail Standalone with Default Settings Source: https://greenmail-mail-test.github.io/greenmail/index This command starts the GreenMail standalone server using the ServerSetup.ALL configuration, which enables all default mail services (SMTP, SMTPS, IMAP, IMAPS, POP3, POP3S, API) with their default ports. No additional dependencies are required beyond the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.setup.all ``` -------------------------------- ### JUnit 4 Rule-Based GreenMail Setup Source: https://greenmail-mail-test.github.io/greenmail/index Demonstrates setting up GreenMail using the GreenMailRule for JUnit 4. This rule automatically manages the lifecycle of the GreenMail server for each test, ensuring a clean environment. It requires the 'com.icegreen:greenmail-junit4' dependency. ```java /** See code on GitHub */ @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()); // ... } ``` -------------------------------- ### Start GreenMail with Offset Ports Source: https://greenmail-mail-test.github.io/greenmail/index This command starts the GreenMail standalone server using the ServerSetupTest.ALL configuration. It enables all default mail services but with an offset of 3000 applied to their default ports, useful for avoiding port conflicts. This requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.setup.test.all ``` -------------------------------- ### Start GreenMail Standalone with all protocols, one user, bound to 0.0.0.0 Source: https://greenmail-mail-test.github.io/greenmail/index This command starts GreenMail with all protocols enabled, configured for a single user, and binds the server to '0.0.0.0', making it accessible from any network interface. It also exposes the API on port 8080. This configuration is useful for testing in environments where the server needs to be accessible externally. ```bash java -Dgreenmail.setup.test.all -Dgreenmail.users=test1:pwd1 \ -Dgreenmail.hostname=0.0.0.0 \ -jar greenmail-standalone.jar ``` -------------------------------- ### Start GreenMail Standalone with SMTP/IMAP and one user Source: https://greenmail-mail-test.github.io/greenmail/index This command starts the GreenMail standalone runner with SMTP on port 3025 and IMAP on port 3143. It configures a single test user 'test1' with password 'pwd1' and email 'test1@localhost'. This setup is ideal for basic SMTP/IMAP testing. ```bash java -Dgreenmail.setup.test.smtp -Dgreenmail.setup.test.imap \ -Dgreenmail.users=test1:pwd1 -jar greenmail-standalone.jar ``` -------------------------------- ### JUnit 5 Extension-Based GreenMail Setup Source: https://greenmail-mail-test.github.io/greenmail/index Illustrates using the GreenMailExtension for JUnit 5, which replaces the JUnit 4 GreenMailRule. This extension also handles the GreenMail server's lifecycle automatically within the test execution. It requires the 'com.icegreen:greenmail-junit5' dependency. ```java /** See code on GitHub */ @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()); } ``` -------------------------------- ### Start GreenMail Standalone with custom SMTP configuration Source: https://greenmail-mail-test.github.io/greenmail/index This command starts GreenMail with only SMTP enabled, configured to run on '127.0.0.1' at port '4025'. This allows for specific testing of the SMTP functionality with a custom port and binding address. ```bash java -Dgreenmail.smtp.hostname=127.0.0.1 -Dgreenmail.smtp.port=4025 \ -jar greenmail-standalone.jar ``` -------------------------------- ### Dynamically Allocate Ports with GreenMail Source: https://greenmail-mail-test.github.io/greenmail/index Illustrates how to configure GreenMail to dynamically choose available ports for its services. This is achieved by setting the port to 0 or using ServerSetup.dynamicPort(). It also includes an example of sending a text email using the dynamically assigned SMTP port. ```java @Rule public final GreenMailRule greenMail = new GreenMailRule(ServerSetup.SMTP.dynamicPort()); GreenMailUtil.sendTextEmail("to@localhost", "from@localhost", "subject", "body", greenMail.getSmtp().getServerSetup()); ``` -------------------------------- ### Enable Verbose Mode for GreenMail Source: https://greenmail-mail-test.github.io/greenmail/index Shows how to enable verbose mode in GreenMail to get debug output and see protocol-level communication. This is demonstrated using the GreenMailRule and the ServerSetup.verbose() method. ```java @Rule public final GreenMailRule greenMail = new GreenMailRule(ServerSetup.verbose(ServerSetupTest.SMTP_IMAP)); ``` -------------------------------- ### Start SMTP Server with Dynamic Port Detection (Java) Source: https://greenmail-mail-test.github.io/greenmail/index Starts an SMTP server that attempts to find an available, unused port. This is useful for avoiding port conflicts when running multiple tests in parallel or when dealing with Windows reserved port ranges. It requires the GreenMail library. ```java /** See code on GitHub */ 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(); } ``` -------------------------------- ### Start GreenMail Standalone with all protocols and two users Source: https://greenmail-mail-test.github.io/greenmail/index This command initiates GreenMail with support for all standard mail protocols (SMTP, SMTPS, IMAP, IMAPS, POP3, POP3S) on their default test ports. It configures two users, 'test1' and 'test2', with specified passwords and domain. This is suitable for comprehensive testing of multiple mail protocols and user accounts. ```bash java -Dgreenmail.setup.test.all -Dgreenmail.users=test1:pwd1,test2:pwd2@example.com \ -jar greenmail-standalone.jar ``` -------------------------------- ### Test Sending/Retrieving with Plain JavaMail and GreenMail (Java) Source: https://greenmail-mail-test.github.io/greenmail/index This example shows how to test email sending via SMTP and retrieving via IMAP using plain JavaMail integrated with GreenMail. It demonstrates creating mail sessions, sending messages, setting up users, connecting to the IMAP store, and retrieving messages. Requires GreenMail and JavaMail dependencies. ```java /** See code on GitHub */ @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]; ... } ``` -------------------------------- ### Configure Hostname and Port for a Protocol Source: https://greenmail-mail-test.github.io/greenmail/index This example demonstrates how to configure a specific hostname (or bind address) and port for a given protocol (e.g., SMTP). The protocol can be smtp, smtps, imap, imaps, pop3, pop3s, or api. The '-Dgreenmail.PROTOCOL.port' option is required unless the protocol is 'api'. This requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.smtp.hostname=127.0.0.1 -Dgreenmail.smtp.port=3025 ``` -------------------------------- ### Test Email Retrieving Code with GreenMail (Java) Source: https://greenmail-mail-test.github.io/greenmail/index Demonstrates how to test email retrieving functionality using GreenMail. It involves starting all email servers on non-default ports, constructing and delivering a MimeMessage, and then asserting the presence of the received message. Requires the GreenMail library. ```java /** See code on GitHub */ //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(); ``` -------------------------------- ### Advanced Email Sending and Retrieving Test (Java) Source: https://greenmail-mail-test.github.io/greenmail/index An advanced example for testing email sending and retrieving using GreenMail. It utilizes random content to prevent test interference and includes assertions for received messages, including multi-part messages. This requires the GreenMail library. ```java /** See code on GitHub */ 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(); ``` -------------------------------- ### Configure log4j using a file for GreenMail Standalone Source: https://greenmail-mail-test.github.io/greenmail/index This option allows overriding the default log4j configuration for the GreenMail standalone runner by providing a custom log4j configuration file. The example shows how to specify a file path. This is useful for customizing logging behavior during testing. ```bash java -Dlog4j.configuration=file:///tmp/log4j.xml -jar greenmail-standalone.jar ``` -------------------------------- ### Configure Mail Session Properties for GreenMail Protocols Source: https://greenmail-mail-test.github.io/greenmail/index This Java code snippet shows how to configure specific mail session properties for GreenMail protocols, such as IMAP. It demonstrates setting 'mail.imap.minidletime' to '100' for the IMAP server setup, and then creating a session that inherits this property. ```java 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 ``` -------------------------------- ### Configure User Login by Email Source: https://greenmail-mail-test.github.io/greenmail/index Starting from version 1.6.1, this option configures GreenMail to use the full email address for login instead of just the local part. This is effective only when users are configured with an '@' symbol (i.e., as an email address) via the -Dgreenmail.users property. Requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.users.login=email ``` -------------------------------- ### Create and Delete Mail Users with GreenMail Source: https://greenmail-mail-test.github.io/greenmail/index Demonstrates how to create new mail users with GreenMail, specifying the email address and password. It also shows how to create a user where the login ID differs from the email address. Finally, it illustrates how to delete a previously created user. ```java 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 ``` -------------------------------- ### Preload Mails from Filesystem Source: https://greenmail-mail-test.github.io/greenmail/index This option (available from 1.6.15/2.0.1/2.1.0-alpha-3) allows preloading emails and user mailboxes from a specified directory on the filesystem. The directory structure dictates user creation and folder organization, with .eml files representing emails. Requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.preload.dir=/tmp/preload-example ``` -------------------------------- ### Configure Users with Passwords and Domains Source: https://greenmail-mail-test.github.io/greenmail/index This option allows preconfiguring user mailboxes with passwords and optional domains. Users are provided as a comma-separated list, where each user is in the format 'local-part:password[@domain]'. This requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.users=foo:pwd@bar.com,jabber:wocky@monster.local,foo1:bar ``` -------------------------------- ### Run GreenMail Standalone Docker image with default ports Source: https://greenmail-mail-test.github.io/greenmail/index This command pulls the GreenMail standalone Docker image (version 2.0.1) and runs it, mapping the default GreenMail ports (SMTP, POP3, IMAP, SMTPS, IMAPS, POP3S, API) from the container to the host machine. This provides a quick way to set up a GreenMail server for testing. ```bash 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 ``` -------------------------------- ### Run GreenMail Standalone Docker image with custom JVM and GreenMail options Source: https://greenmail-mail-test.github.io/greenmail/index This command runs the GreenMail standalone Docker image, allowing customization of JVM and GreenMail options through environment variables. It sets specific GreenMail options (e.g., enabling all protocols, disabling authentication, enabling verbose logging) and Java options (e.g., preferred IPv4 stack, max heap size), and maps the necessary ports. This offers advanced control over the GreenMail server's behavior within Docker. ```bash 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 ``` -------------------------------- ### Configure TLS Keystore for Secure Connections Source: https://greenmail-mail-test.github.io/greenmail/index These options (available from 1.6.8/2.0.0) configure a PKCS12 keystore file and its password for enabling secure IMAP/SMTP/POP3 TLS connections. The key password can also be specified separately if it differs from the keystore password (available from 1.6.15/2.0.1/2.1.0-alpha-3). Requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.tls.keystore.file=/home/greenmail/greenmail.p12 -Dgreenmail.tls.keystore.password=changeit ``` ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.tls.keystore.file=/home/greenmail/greenmail.p12 -Dgreenmail.tls.keystore.password=changeit -Dgreenmail.tls.key.password=changeit4key ``` -------------------------------- ### Test Email Receiving with GreenMail JUnit Rule (Java) Source: https://greenmail-mail-test.github.io/greenmail/index Illustrates using the GreenMail JUnit rule to test email retrieval via POP3 or IMAP. It sets up a server, delivers messages, and asserts the number of received messages. Requires the greenmail-junit4 dependency. ```java @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 } ``` -------------------------------- ### Spring Framework Integration with GreenMailBean (Java) Source: https://greenmail-mail-test.github.io/greenmail/index Demonstrates how to integrate GreenMail with the Spring framework using the `GreenMailBean`. This allows for easy dependency injection of GreenMail into Spring-managed components for email testing. Requires the `greenmail-spring` module. ```java /** See GreenMailBeanTest.java * and GreenMailBeanTest-context.xml */ @Autowired private GreenMailBean greenMailBean; @Test public void testCreate() { GreenMail greenMail = greenMailBean.getGreenMail(); ... } ``` -------------------------------- ### Test Email Sending with GreenMail JUnit Rule (Java) Source: https://greenmail-mail-test.github.io/greenmail/index Demonstrates how to use the GreenMail JUnit rule to test email sending functionality. It sets up an SMTP server and verifies received messages. Requires the greenmail-junit4 dependency. ```java @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()); } ``` -------------------------------- ### Configure Default Hostname and Specific Ports Source: https://greenmail-mail-test.github.io/greenmail/index This command sets a default hostname for all protocols and specifies individual ports for certain protocols like SMTP and IMAP. The default hostname is used if a protocol-specific hostname is not provided. This requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.smtp.port=3025 -Dgreenmail.imap.port=3143 -Dgreenmail.hostname=0.0.0.0 ``` -------------------------------- ### Enable Verbose Logging Source: https://greenmail-mail-test.github.io/greenmail/index This option enables verbose mode for the GreenMail standalone server. It is useful for debugging purposes, providing detailed output at the debug and protocol levels. Requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.verbose ``` -------------------------------- ### Override GreenMail Initialization for Nested Test Classes Source: https://greenmail-mail-test.github.io/greenmail/index This Java code demonstrates how to override the `beforeAll` method in GreenMailExtension to prevent redundant initialization when using nested test classes. It checks if the current class is a non-static inner class and skips super.beforeAll() if it is, avoiding 'Address already in use' errors. ```java 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 } } } ``` -------------------------------- ### Disable User Authentication Source: https://greenmail-mail-test.github.io/greenmail/index This option disables the user authentication check, allowing any password to be accepted for any user. This is useful when you don't want to preconfigure users and passwords, as GreenMail will automatically create non-existent users. Requires the GreenMail standalone JAR. ```bash java [OPTIONS] -jar greenmail-standalone.jar -Dgreenmail.auth.disabled ``` -------------------------------- ### Directly Search Received Messages with GreenMail Source: https://greenmail-mail-test.github.io/greenmail/index This Java code illustrates how to directly search received messages within GreenMail without using IMAP or POP3 protocols. It uses predicates to filter users by email and messages by subject, collecting the matching messages into a List. Requires GreenMail 2.1.0+. ```java // 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()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.