我使用下面的代码向“ksjdcbnjkhbvsmdbsdb@gmail.com”(不存在的电子邮件)发送邮件。由于该电子邮件地址不存在,因此电子邮件应该已退回。我想获取失败消息,但我的代码不会打印此失败消息。这里有什么问题,我该如何获得失败信息?
import smtplib
import email
import imaplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def processNewTripData(request):
# process trip data
templateName = "sendmail.html"
mapDictionary = {'fromMail': "xxx@gmail.com", 'password': "xxxx", 'toMail': "ksjdcbnjkhbvsmdbsdb@gmail.com","subject": "New Trip ", 'username': 'Ram','trip_start_date' : '2014-02-10','trip_start_place' : 'Visaka', 'trip_start_time' : '11:00 AM', "templateName" : templateName }
return sendMail(request, mapDictionary)
def sendMail(request, mapDictionary):
try:
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(mapDictionary["fromMail"],mapDictionary["password"])
context = Context(mapDictionary)
html_content = render_to_string(mapDictionary["templateName"], context)
#text_content = "This is Confirmation mail"
msg = MIMEText(html_content,'html')
msg['Subject'] = mapDictionary["subject"]
server.sendmail(mapDictionary["fromMail"], mapDictionary['toMail'],msg.as_string())
if (msg.is_multipart() and len(msg.get_payload()) > 1 and msg.get_payload(1).get_content_type() == 'message/delivery-status'):
# email is DSN
print(msg.get_payload(0).get_payload()) # human-readable section
for dsn in msg.get_payload(1).get_payload():
print('action: %s' % dsn['action']) # e.g., "failed", "delivered"
to_json = {'result' : "True"}
except Exception as e:
print str(e)
to_json = {'result' : "False"}
答案 0 :(得分:2)
无法保证在您的会话开放时报告失败。 SMTP基本上是存储转发协议;您应该期望消息由中继处理,该中继不知道最终目的地是否可达。即使您直接连接到Google指定的MX,它们也可能具有内部路由,其工作方式与此类似。一些域名也推迟报告错误,以减缓垃圾邮件发送者的速度(尝试投放将是检查哪些地址有效的好方法。事实上,你正在做的事情可能看起来就像你是一个新手垃圾邮件发送者,所以他们可以将您的IP地址放在主机列表中以进行“特殊”处理。)