Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect bounced emails in Python smtplib

I'm trying to catch all emails that bounced when sending them via smtplib in Python. I looked at this similar post which suggested adding an exception catcher, but I noticed that my sendmail function doesn't throw any exceptions even for fake email addresses.

Here is my send_email function which uses smtplib.

def send_email(body, subject, recipients, sent_from="[email protected]"):
    msg = MIMEText(body)

    msg['Subject'] = subject
    msg['From'] = sent_from
    msg['To'] = ", ".join(recipients)

    s = smtplib.SMTP('mySmtpServer:Port')
    try:
       s.sendmail(msg['From'], recipients, msg.as_string())
    except SMTPResponseException as e:
        error_code = e.smtp_code
        error_message = e.smtp_error
        print("error_code: {}, error_message: {}".format(error_code, error_message))
    s.quit()

Sample call:

send_email("Body-Test", "Subject-Test", ["[email protected]"], "[email protected]")

Since I set the sender as myself, I am able to receive the email bounce report in my sender's inbox:

<[email protected]>: Host or domain name not found. Name service error
    for name=jfdlsaf.com type=A: Host not found

Final-Recipient: rfc822; [email protected]
Original-Recipient: rfc822;[email protected]
Action: failed
Status: 5.4.4
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error
    for name=jfdlsaf.com type=A: Host not found

Is there a way to get the bounce message through Python?

like image 243
Kevin Avatar asked Nov 01 '16 22:11

Kevin


People also ask

How do you know if an email is bounced?

Go to Add-ons > Mail Merge > Campaign Reports > View Bounced Email to view your bounce report. The report is for your entire Google account and not specific to any email campaign. It may thus include email addresses that were found in your mailbox but could have been sent manually.

What does Smtplib SMTP do?

The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon.

How do I use Smtplib in Python 3?

Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon. host − This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com.

How do you manage email bounces?

Try sending an email to the "Undeliverable" email address again. If the address keeps bouncing, you should remove it from your lists. If possible, get in touch with the contact to see if they have a new email address.


1 Answers

import poplib
from email import parser

#breaks with if this is left out for some reason (MAXLINE is set too low by default.)
poplib._MAXLINE=20480

pop_conn = poplib.POP3_SSL('your pop server',port)
pop_conn.user(username)
pop_conn.pass_(password)
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]

# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    if "Undeliverable" in message['subject']:

        print message['subject']
        for part in message.walk():
            if part.get_content_type():
                body = str(part.get_payload(decode=True))

                bounced = re.findall('[a-z0-9-_\.]+@[a-z0-9-\.]+\.[a-z\.]{2,5}',body)
                if bounced:

                    bounced = str(bounced[0].replace(username,''))
                    if bounced == '':
                        break

                    print bounced 

Hope this helps. This will check the contents of the mailbox for any undeliverable reports and read the message to find the email address that bounced.It then prints the result

like image 158
alex Avatar answered Oct 17 '22 19:10

alex