【问题标题】:Detect bounced emails in Python smtplib在 Python smtplib 中检测退回的电子邮件
【发布时间】:2017-03-15 03:46:37
【问题描述】:

我正在尝试捕获所有在 Python 中通过 smtplib 发送时退回的电子邮件。我查看了这个建议添加异常捕获器的similar post,但我注意到我的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()

示例调用:

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

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

<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

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

【问题讨论】:

  • 你有解决办法吗?
  • 也许使用 poplib 打开您的邮箱,您的退回报告将被发送到?

标签: python email smtp mime smtplib


【解决方案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 

希望这会有所帮助。这将检查邮箱内容中是否有任何无法投递的报告,并阅读邮件以找到退回的电子邮件地址。然后打印结果

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2021-12-18
    • 2011-10-04
    • 2021-04-26
    • 2011-02-12
    • 2017-06-27
    • 2013-04-15
    • 2017-06-20
    • 2023-03-26
    相关资源
    最近更新 更多