Python SMTP 错误代码处理

问题描述 投票:0回答:2

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

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

import smtplib
from smtplib import *

sender = '[email protected]'
receivers = ['[email protected]']

message = """From: From Arthur <[email protected]>
To: To Deep Thought <[email protected]>
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,'[email protected]')
  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 [email protected] instead of [email protected])"
  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 文档说 otheriwse)所以我也尝试过,但我不确定传递其构造函数的参数(代码, 消息).

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

谢谢。

python python-2.7 smtp smtplib error-code
2个回答
7
投票

尝试

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

0
投票

我们可以在 SMTP_ERROR_CODES dict 中添加更多错误代码和错误详细信息。

import smtplib
from bs4 import BeautifulSoup
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


SMTP_ERROR_CODES = {
    211: "System status, or system help reply.",
    214: "Help message.",
    220: "Service ready.",
    221: "Service closing transmission channel.",
    235: "Authentication successful.",
    250: "Requested mail action okay, completed.",
    251: "User not local; will forward to {}",
    252: "Cannot VRFY user, but will accept message and attempt delivery.",
    354: "Start mail input; end with <CRLF>.<CRLF>",
    421: "Service not available, closing transmission channel. The server response was: {}",
    450: "Requested mail action not taken: mailbox unavailable. The server response was: {}",
    451: "Requested action aborted: local error in processing.",
    452: "Requested action not taken: insufficient system storage.",
    455: "Server unable to accommodate parameters.",
    500: "Syntax error, command unrecognized.",
    501: "Syntax error in parameters or arguments.",
    502: "Command not implemented.",
    503: "Bad sequence of commands.",
    504: "Command parameter not implemented.",
    530: "Authentication required.",
    534: "Authentication mechanism is too weak.",
    535: "Authentication failed. The server response was: {}",
    538: "Encryption required for requested authentication mechanism.",
    550: "Requested action not taken: mailbox unavailable. The server response was: {}",
    551: "User not local; please try {}. The server response was: {}",
    552: "Requested mail action aborted: exceeded storage allocation.",
    553: "Requested action not taken: mailbox name not allowed.",
    554: "Transaction failed. The server response was: {}",
}

    try:
        msg = MIMEMultipart(
            "alternative", None, [MIMEText(html_content, 'html')])
        msg['From'] = sender
        msg['To'] = ", ".join(recipients)
        msg['Subject'] = f"email report.!"
        server = smtplib.SMTP('example.com', 587)
        server.starttls()
        text = msg.as_string()
        server.sendmail(sender, recipients, text)
        server.quit()
        log.info("Successfully result was sent to the recipient email")
    except smtplib.SMTPResponseException as err:
        error_code = err.smtp_code
        error_message = SMTP_ERROR_CODES.get(error_code, f"Unknown error ({error_code})")
        log.error(f"Observed exception while send email to recipient email!,\n "
                  f"Exception: {error_message.format(err.smtp_error)}")
    except Exception as Err:
        log.error(f"Observed exception while send email to recipient email!,\n "
                  f"Exception: {Err}")
© www.soinside.com 2019 - 2024. All rights reserved.