2014-01-12 62 views
2
import smtplib 

sender = '[email protected]' 
receiver = ['[email protected]'] 

message = """From: From Person <[email protected]> 
To: To Person <[email protected]> 
Subject: SMTP e-mail test 

This is a test e-mail message. 
""" 

try: 

    print("trying host and port...") 

    smtpObj = smtplib.SMTP('smtp.gmail.com', 465) 

    print("sending mail...") 

    smtpObj.sendmail(sender, receiver, message) 

    print("Succesfully sent email") 

except SMTPException: 

    print("Error: unable to send email") 

我創建了兩個新的電子郵件帳戶(上面),都在同一臺服務器(gmail)上進行測試。 它達到了打印「嘗試主機和端口...」的程度,並且不再進一步。所以問題應該是我輸入的地址和端口號。但根據Gmail的傳出郵件服務器的詳細信息,我已經正確地輸入了它們。任何想法有什麼不對?沒有使用smtplib發送電子郵件 - python

如果我刪除端口號或嘗試不同的端口號,如587我提供了一個錯誤。

+0

啓用從'smtplib'診斷,所以你能看到它會錯了。在這個細節層面上,我們所能做的只是猜測。我的猜測是Gmail需要驗證,在這種情況下,請查看任何近乎重複的英國郵件。 – tripleee

回答

1

Sending email via Gmail's SMTP servers requires TLS和認證。要進行身份驗證,您需要make an application-specific password for your account

此腳本適用於我(儘管我使用了我自己的GMail電子郵件地址和我自己的應用程序專用密碼)。在下面的代碼中,將APPLICATION_SPECIFIC_PASSWORD替換爲您生成的密碼。

import smtplib 

sender = '[email protected]' 
receiver = ['[email protected]'] 

message = """From: From Person <[email protected]> 
To: To Person <[email protected]> 
Subject: SMTP e-mail test 

This is a test e-mail message. 
""" 

try: 
    print("trying host and port...") 

    smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
    smtpObj.login("[email protected]", "APPLICATION_SPECIFIC_PASSWORD") 

    print("sending mail...") 

    smtpObj.sendmail(sender, receiver, message) 

    print("Succesfully sent email") 

except smtplib.SMTPException: 
    print("Error: unable to send email") 
    import traceback 
    traceback.print_exc() 

(調試問題,我加在打印追溯碼except語句。唯一的例外就如何得到它的工作的具體信息。該代碼當雄接入端口465,我想是因爲問題TLS協商,所以我不得不使用端口587去嘗試,然後我得到的解釋做什麼很好的調試信息)

You can see info on the SMTP_SSL object here.

相關問題