2013-07-09 107 views
2

我使用下面的代碼使用python stmp lib發送電子郵件。但是當我在unix中執行代碼時,控制檯等待,好像它在等待我輸入內容。我必須按Ctrl + Z才能退出程序。在Python中使用smtp發送電子郵件不起作用

#!/usr/bin/python 

import smtplib 
from email.mime.text import MIMEText 
textfile = '/my/folder/file.log' 
fp = open(textfile, 'rb') 
msg = MIMEText(fp.read()) 
fp.close() 
msg['Subject'] = 'The contents of %s' % textfile 
msg['From'] = "[email protected]" 
msg['To'] = "[email protected]" 
s = smtplib.SMTP('company.server.name') 
s.sendmail("[email protected]", "[email protected]", msg.as_string()) 
s.quit() 

你能告訴我哪裏出錯了嗎?

+1

在這些行之間放置'print'語句來找出卡住的位置。另外,請注意,Ctrl-Z不會退出程序,它只是暫停它。您可能會暫停這些進程中的一些進程,這可能會產生影響,具體取決於他們持有哪些資源。 – kwatford

+1

此外,如果您按Ctrl-C而不是Ctrl-Z,則不僅會退出該程序,還會打印一個回溯,顯示Python被卡住的位置。如果回溯中的第一行是's = smtplib.SMTP('company.server.name')',那麼您知道問題是連接到或登錄到服務器。如果它是'.sendmail(blah blah)',你就知道它正在發送消息。等等。 – abarnert

+0

我被困在's = smtplib.SMTP('company.server.name')' – misguided

回答

0

由於@kwatford的意見建議使用打印語句嘗試,發現該代碼執行陷在

s = smtplib.SMTP('company.server.name')

的作爲@abarnert建議,試圖

telnet company.server.name

與失敗,錯誤

telnet: Unable to connect to remote host: Connection timed out

因此基本代碼不能夠連接到SMTP服務器造成的問題。

+0

感謝您的解釋。請接受這個答案。 –