Python SMTP 错误代码处理

Posted

技术标签:

【中文标题】Python SMTP 错误代码处理【英文标题】:Python SMTP error code handling 【发布时间】:2016-02-06 07:59:05 【问题描述】:

我对此进行了相当多的搜索,但找不到任何令人满意的结果。

我一直在尝试编写一个 python 程序来监听电子邮件退回报告,并根据退回的原因以不同的时间间隔重新发送它们。

import smtplib
from smtplib import *

sender = 'foo@bar.com'
receivers = ['42@life.com']

message = """From: From Arthur <foo@bar.com>
To: To Deep Thought <42@life.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""

try:
  smtpObj = smtplib.SMTP('smtp.gmail.com',587)
  smtpObj.starttls()
  smtpObj.login(sender,'foo@bar.com')
  smtpObj.sendmail(sender, receivers, message)
  print "Successfully sent email"
except SMTPResponseException:
  error_code = SMTPResponseException.smtp_code
  error_message = SMTPResponseException.smtp_error
  print "Error code:"+error_code
  print "Message:"+error_message
  if (error_code==422):
    print "Recipient Mailbox Full"
  elif(error_code==431):
    print "Server out of space"
  elif(error_code==447):
    print "Timeout. Try reducing number of recipients"
  elif(error_code==510 or error_code==511):
    print "One of the addresses in your TO, CC or BBC line doesn't exist. Check again your recipients' accounts and correct any possible misspelling."
  elif(error_code==512):
    print "Check again all your recipients' addresses: there will likely be an error in a domain name (like mail@domain.coom instead of mail@domain.com)"
  elif(error_code==541 or error_code==554):
    print "Your message has been detected and labeled as spam. You must ask the recipient to whitelist you"
  elif(error_code==550):
    print "Though it can be returned also by the recipient's firewall (or when the incoming server is down), the great majority of errors 550 simply tell that the recipient email address doesn't exist. You should contact the recipient otherwise and get the right address."
  elif(error_code==553):
    print "Check all the addresses in the TO, CC and BCC field. There should be an error or a misspelling somewhere."
  else:
    print error_code+": "+error_message

我收到以下错误:

Traceback(最近一次调用最后一次):文件“C:/Users/Varun Shijo/PycharmProjects/EmailBounce/EmailBounceTest.py”,第 20 行,在 error_code = SMTPResponseException.smtp_code AttributeError:类型对象“SMTPResponseException”没有属性“smtp_code”

我在某处读到我应该尝试从 SMTPResponseException 类的实例中获取属性(即使 smtplib 文档说其他)所以我也尝试过,但我不确定传递其构造函数的参数是什么(代码,消息)。

有人可以把我推到正确的方向吗?

谢谢。

【问题讨论】:

【参考方案1】:

试试

except SMTPResponseException as e:
    error_code = e.smtp_code
    error_message = e.smtp_error

【讨论】:

非常感谢!这行得通。如果我理解正确,那么通过在捕获异常时将参数隐式传递给构造函数来处理实例化,对吗? 你好。异常在引发时被实例化。我提供的代码只是告诉 python 为它创建一个名称e。属性由异常类的构造函数设置。请看this SO QA

以上是关于Python SMTP 错误代码处理的主要内容,如果未能解决你的问题,请参考以下文章

我无法发送电子邮件 smtp 错误

Python 新手,GMail SMTP 错误

使用 smtp 和 Python 发送电子邮件时出现 SSL 错误

Python 使用 smtplib 发邮件,显示错误 [Errno 10060] A connection attempt failed because……

Amazon SES - SMTP 错误状态代码 403:SignatureDoesNotMatch

smtplib.SMTP starttls 因 tlsv1 警报解码错误而失败