2013-01-11 119 views
-1

以下是我的腳本來連接到SMTP服務器和發送郵件。無法使用python腳本連接到SMTP服務器

from smtplib import SMTP 
import datetime 

debuglevel = 0 

smtp = SMTP() 
smtp.set_debuglevel(debuglevel) 
smtp.connect('smtp.gmail.com', 26) 
smtp.login('[email protected]', 'Pa***wd') 

from_addr = "Ashwin<[email protected]>" 
to_addr = "[email protected]" 

subj = "hello" 
date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") 

message_text = "Hello\nThis is a mail from your server\n\nBye\n" 

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"%(from_addr, to_addr, subj, date, message_text) 

smtp.sendmail(from_addr, to_addr, msg) 
smtp.quit() 

但它引發以下錯誤: -

Traceback (most recent call last): 
    File "C:\Python33\Bidhoo.py", line 15, in <module> 
    smtp.connect('smtp.gmail.com', 26) 
    File "C:\Python33\lib\smtplib.py", line 317, in connect 
    self.sock = self._get_socket(host, port, self.timeout) 
    File "C:\Python33\lib\smtplib.py", line 288, in _get_socket 
    self.source_address) 
    File "C:\Python33\lib\socket.py", line 424, in create_connection 
    raise err 
    File "C:\Python33\lib\socket.py", line 415, in create_connection 
    sock.connect(sa) 
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 

請幫我找到這個錯誤的根源。也可以有人共享備用代碼連接到SMTP ..

+0

歡迎來到Stack Overflow!爲了更好地解答您的問題,請閱讀並牢記[如何問](http://stackoverflow.com/questions/how-to-ask)文章。 –

回答

2

我認爲這是smtp.connect行失敗?您可以通過在Python解釋器中逐行運行腳本來驗證這一點。

這是失敗的原因是因爲端口號不正確。嘗試587而不是26,看看會發生什麼。

smtp.connect('smtp.gmail.com', 587) 

至於替代腳本,我發現了一些谷歌搜索的腳本。這裏的one

+0

使用上述方法觀察到的錯誤[將端口更改爲587] – user1969147

相關問題