我试图抓住所有通过Python中的smtplib发送的电子邮件。我查看了similar post,建议添加异常捕获器,但我注意到我的send_email
函数即使对于虚假的电子邮件地址也不会抛出任何异常。
以下是我使用smtplib
的{{1}}函数。
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获取退回邮件?
答案 0 :(得分: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
希望这会有所帮助。这将检查邮箱的内容是否有任何无法投递的报告,并阅读邮件以查找退回的电子邮件地址。然后打印结果