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

2024-06-26 14:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕捉所有在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()

示例电话:

^{pr2}$

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

<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获取bounce消息?在


Tags: namecomhostmessage邮件notcodemsg
1条回答
网友
1楼 · 发布于 2024-06-26 14:47:31
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 

希望这有帮助。这将检查邮箱中是否有任何无法送达的报告,并阅读邮件以找到弹跳了。它然后打印结果

相关问题 更多 >