I'm using GreenMail in a test to verify that our application is sending email correctly.
I start GreenMail with:
GreenMail greenMailServer = new GreenMail(new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP));
greenMailServer.start();
I have a separate process that sends the email to the GreenMail SMTP server (this is part of an integration test), so my test code waits for the email with:
long endTime = System.currentTimeMillis() + timeout;
// Get the fake mail server and listen for messages
GreenMail mailServer = ITester.getFakeEMail();
while(System.currentTimeMillis() < endTime) {
boolean timedOut = !mailServer.waitForIncomingEmail(endTime - System.currentTimeMillis(), 1);
if(timedOut) {
throw new TestFailure(lineNumber, "Timed out waiting for email To: '"+to+"' Subject: '"+subject+"' Body: '"+body+"' .");
}
for(MimeMessage message : mailServer.getReceivedMessages()) {
try {
StringBuilder errors = new StringBuilder();
// Check who the message is going to
//Address[] allRecipients = message.getRecipients(Message.RecipientType.BCC);
Address[] allRecipients = message.getAllRecipients();
I've tried both the commented out request for Recipients and the getAllRecipients, but I always receive null. I've verified that my application is sending the email to one address in the BCC field.
Any idea why I'm not seeing the recipient email address?
I found the answer on this blog:
https://developer.vz.net/2011/11/08/unit-testing-java-mail-code/
The short version is to use a user and get the message from his inbox instead of getting the message from the server as a whole. Then you know it came to that email address.
GreenMailUser user = mailServer.setUser("junk@somewhere.com", "");
MailFolder inbox = mailServer.getManagers().getImapHostManager().getInbox(user);
for(StoredMessage message : inbox.getMessages()) {
// Verify the messages
}