gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:48:18 29 4
gpt4 key购买 nike

我正在 try catch 通过 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获取退回邮件?

最佳答案

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

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

关于python - 在 Python smtplib 中检测退回的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369645/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com