To add a more recent answer to this question and as the linked blog post from 2012 seems to be down occasionally, here's a full example of using GreenMail for writing integration tests with JUnit 5 (assuming you're using Spring Boot's auto-configuration for the JavaMailSender
).
First, make sure to override the credentials and location of the mail server. You can add an application.yml
file inside src/test/resources
for this purpose:
spring:
mail:
password: springboot
username: duke
host: 127.0.0.1
port: 3025 # default protocol port + 3000 as offset
protocol: smtp
test-connection: true
Next, Spring Boot's auto-configuration will configure the JavaMailSender
to connect to GreenMail for your tests. You can use GreenMail's JUnit Jupiter extension to conveniently start/stop a GreenMail server for your tests:
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail-junit5</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
... resulting in the following sample test:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class JavaMailSenderIT {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP)
.withConfiguration(GreenMailConfiguration.aConfig().withUser("duke", "springboot"))
.withPerMethodLifecycle(false);
@Autowired
private JavaMailSender javaMailSender;
@Test
void shouldUseGreenMail() throws Exception {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom("[email protected]");
mail.setSubject("A new message for you");
mail.setText("Hello GreenMail!");
mail.setTo("[email protected]");
javaMailSender.send(mail);
// awaitility
await().atMost(2, SECONDS).untilAsserted(() -> {
MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
assertEquals(1, receivedMessages.length);
MimeMessage receivedMessage = receivedMessages[0];
assertEquals("Hello GreenMail!", GreenMailUtil.getBody(receivedMessage));
assertEquals(1, receivedMessage.getAllRecipients().length);
assertEquals("[email protected]", receivedMessage.getAllRecipients()[0].toString());
});
}
}
You can also use Testcontainers to start a local GreenMail container as your local sandbox email server.