0
我正在使用以下代碼向「[email protected]」(不存在的電子郵件)發送郵件。由於該電子郵件地址不存在,因此電子郵件應該已被退回。我想獲取失敗消息,但我的代碼不打印此失敗消息。這裏有什麼問題,我應該如何得到失敗信息?將郵件發送到不存在的地址時檢索失敗消息
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': "[email protected]", 'password': "xxxx", 'toMail': "[email protected]","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"}
即使接近準確度,處理這種情況的唯一方法是設置一個Reply-To標題,以便任何退回消息可以由一個單獨的程序處理。在過去,我已經實現了讀取消息和處理來自各種SMTP服務器的各種格式的錯誤消息的邏輯,我知道並非所有服務器在引發錯誤消息時都會操作Reply-To頭部,並且一些服務器配置爲不會引發退回消息在所有。在我的項目中有信用卡欺詐潛力。所以,我們可以越少反彈越少,我們被欺騙,這是值得執行的。 – holdenweb