Обработка кода ошибки Python SMTP

Я искал справедливо немного по этому поводу и не мог придумать ничего удовлетворительного.

Я пытался написать программу 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

На что я получаю следующую ошибку:

Трассировка (последний последний вызов): файл «C:/Users/Varun Shijo/PycharmProjects/EmailBounce/EmailBounceTest.py», строка 20, в error_code = SMTPResponseException.smtp_code AttributeError: объект типа «SMTPResponseException» не имеет атрибута «smtp_code»

Я где-то читал, что должен попытаться получить атрибут из экземпляра класса SMTPResponseException (хотя в документации по smtplib указано otheriwse), поэтому я тоже попробовал, но не был уверен, какие аргументы передать его конструктору (код, сообщение).

Может ли кто-нибудь подтолкнуть меня в правильном направлении?

Спасибо.


person Varun Shijo    schedule 05.11.2015    source источник


Ответы (1)


попробуй с

except SMTPResponseException as e:
    error_code = e.smtp_code
    error_message = e.smtp_error
person Pynchia    schedule 05.11.2015
comment
Большое спасибо! Это сработало. Если я правильно понимаю, делая это, вы обрабатываете создание экземпляра, неявно передавая аргументы конструктору при обнаружении исключения, верно? - person Varun Shijo; 07.11.2015
comment
Привет. Исключение создается при его возникновении. Код, который я предоставил, просто говорит python создать для него имя e. Атрибуты задаются конструктором класса исключений. Пожалуйста, взгляните на эту SO QA - person Pynchia; 07.11.2015