Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GreenMail not returning BCC recipient addresses

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?

like image 458
Stephen M -on strike- Avatar asked Jan 27 '26 05:01

Stephen M -on strike-


1 Answers

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("[email protected]", "");
MailFolder inbox = mailServer.getManagers().getImapHostManager().getInbox(user);
for(StoredMessage message : inbox.getMessages()) {
   // Verify the messages
}
like image 146
Stephen M -on strike- Avatar answered Jan 29 '26 18:01

Stephen M -on strike-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!