Email Bounce Detection

Maric Michaud maric at
Fri Jun 27 09:34:22 CEST 2008

Le Friday 27 June 2008 09:03:15 madhav, vous avez écrit :
> Hello everybody, I need a mechanism to detect email bounces. I tried
> browsing through smtplib implementation and found not helpful in this
> case. Actually it is said in the documentation that if a mail is sent
> to say: "somerandomname at", then "_send()" in the
> SMTPConnection class returns 550(Unknown recceipient). I checked the
> same but its not returning 550 and return 250(receipient ok).

This is not the same scenario, the SMTP server that will respond 550 is the MX 
for the domain, if you send your mails using an outgoing SMTP server, it 
can't know in advance the list of remote adressesbut will bounce your message 
when receiving the 550 from the remote MX.

> Later, I tried getting the smtp error code from the mail body of a
> bounced msg. the "Message" class doesnot have any error code attribute
> by default. We need to get it from the mailbody(by regex ing), which i
> think is not a valid solution, as "550" can occur anywhere in the body
> of any message otherthan the bounced msg also.
> Please help me regarding this.
> Thanks in advance.

Bounces are multipart messages easily parsed with the email package of the 
stdlib (dont' use regexes here).

Abounce message is of type :

Content-Type: multipart/report;

a delivery-status imply that one of the subpart of the message is a 
message/delivery-status with all needed infos set in the headers. This one is 
taken from a real example :

Content-Description: Delivery report
Content-Type: message/delivery-status

Reporting-MTA: dns;
X-Postfix-Queue-ID: 1D07D1409FF
X-Postfix-Sender: rfc822; maric at
Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST)

Final-Recipient: rfc822; unknownadress at
Original-Recipient: rfc822;unknownadress at
Action: failed
Status: 5.0.0
Remote-MTA: dns;
Diagnostic-Code: smtp; 550 <unknownadress at>: Recipient address 
    User unknown in local recipient table

So, for example :

>>>[48]: import email

>>>[49]: bounce = email.message_from_string(open('ex.eml').read())

>>>[50]: bounce.get_content_type()
...[50]: 'multipart/report'


>>>[52]: for i in bounce.get_payload() :
   ....:    if i.get_content_type() == 'message/delivery-status' :
   ....:         print i.get_payload()[1]['status']


Maric Michaud

More information about the Python-list mailing list