2014-02-28 15 views
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"} 

回答

2

無法保證會話打開時會報告失敗。 SMTP基本上是存儲轉發協議;您應該期望消息由不知道最終目的地是否可達的中繼處理。即使您直接連接到Google的指定MX,他們也可能有內部路由,其工作方式與此完全相同。有些域名也阻止了報告錯誤,以減慢垃圾郵件發送者的速度(嘗試發送郵件是檢查哪些地址有效的好方法,事實上,你在做什麼可能會讓Google看起來像你是一個新手垃圾郵件發送者,所以他們可能會把你的IP地址放在主機列表中以給予「特殊」處理)。

+0

即使接近準確度,處理這種情況的唯一方法是設置一個Reply-To標題,以便任何退回消息可以由一個單獨的程序處理。在過去,我已經實現了讀取消息和處理來自各種SMTP服務器的各種格式的錯誤消息的邏輯,我知道並非所有服務器在引發錯誤消息時都會操作Reply-To頭部,並且一些服務器配置爲不會引發退回消息在所有。在我的項目中有信用卡欺詐潛力。所以,我們可以越少反彈越少,我們被欺騙,這是值得執行的。 – holdenweb

相關問題