简体   繁体   中英

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?

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());


    }

The information that you are looking for (Action, Final-Recipient, Diagnostic-Code, Status) are set in the headers of the message, you can get it with

Considering that msg is the message object:

  ... 
  final String[] diagnostics = msg.getHeader("Diagnostic-Code"); 

  for (String dx_code : diagnostics) {
     System.out.print(dx_code);
  }
  ...

the second value (in the example diagnostics[1] ) will contain the error code that indicates if it is a hard bounce 550 (for instance the email address does not exist), or a soft bounce 450 (for example, the inbox bin is full)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM