Skip to content
Advertisement

How to read a bounce back email details with Java mail API?

I am using Java mail API to read the bounce back email from Amazon SES on my Gmail id.

This is how I receive an bounce email from Amazon SES.

<email content start>

An error occurred while trying to deliver the mail to the following recipients:
bounce@simulator.amazonses.com
Action: failed
Final-Recipient: rfc822; bounce@simulator.amazonses.com
Diagnostic-Code: smtp; 550 5.1.1 user unknown
Status: 5.1.1



---------- Forwarded message ----------
From: fullstack.rahultokase@gmail.com
To: bounce@simulator.amazonses.com
Cc: 
Bcc: 
Date: Sun, 17 Dec 2017 15:27:30 +0000
Subject: bounce@simulator.amazonses.com
bounce@simulator.amazonses.com

<email content end>

My question is using Java email API. I am able to read the content up to:

An error occurred while trying to deliver the mail to the following recipients:
bounce@simulator.amazonses.com

But I am not able to read the following content with the help of Java email api

Action: failed
Final-Recipient: rfc822; bounce@simulator.amazonses.com
Diagnostic-Code: smtp; 550 5.1.1 user unknown
Status: 5.1.1

How can I read the above content in the email?

Advertisement

Answer

The diagnostic code information is a part of message content and can be read using the following code.

MimeMessage payload = (MimeMessage) message.getPayload();
    Multipart mp = (Multipart) payload.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
                        BodyPart bodyPart = mp.getBodyPart(i);
                        StringWriter writer = new StringWriter();
                        IOUtils.copy(bodyPart.getInputStream(), writer);
                        System.out.println("Content inputstream: " +  writer.toString());


    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement