检测Python smtplib中的退回电子邮件

Kev*_*vin 7 python email mime smtp smtplib

我正在尝试捕获所有通过Python中的smtplib发送它们时反弹的电子邮件.我查看了这个类似的帖子,建议添加一个异常捕获器,但我注意到我的sendmail函数不会抛出任何例外,即使是假的电子邮件地址.

这是我send_email使用的功能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()
Run Code Online (Sandbox Code Playgroud)

示例电话:

send_email("Body-Test", "Subject-Test", ["fakejfdklsa@jfdlsaf.com"], "myemail@server.com")
Run Code Online (Sandbox Code Playgroud)

由于我将发件人设置为自己,因此我可以在发件人的收件箱中收到电子邮件退回报告:

<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
Run Code Online (Sandbox Code Playgroud)

有没有办法通过Python获取退回消息?

ale*_*lex 2

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 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。这将检查邮箱的内容是否有任何无法送达的报告,并阅读消息以查找退回的电子邮件地址。然后打印结果