Detecting returned emails in Python smtplib

I am trying to catch all the emails that bounce when sending them via smtplib in Python. I looked at this similar post that suggested adding an exception trap, but I noticed that my function sendmaildoes not throw any exceptions even for fake email addresses.

Here is my function send_emailthat uses smtplib.

def send_email(body, subject, recipients, sent_from="myEmail@server.com"):
    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()

Call example:

send_email("Body-Test", "Subject-Test", ["fakejfdklsa@jfdlsaf.com"], "myemail@server.com")

Since I set the sender as myself, I can get an email failure report in the inbox:

<fakejfdklsa@jfdlsaf.com>: Host or domain name not found. Name service error
    for name=jfdlsaf.com type=A: Host not found

Final-Recipient: rfc822; fakejfdklsa@jfdlsaf.com
Original-Recipient: rfc822;fakejfdklsa@jfdlsaf.com
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 a bounce message through Python?

+4
1
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 

, . , , .

0

Source: https://habr.com/ru/post/1659562/


All Articles