2013-07-09 110 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

感谢您的解释。请接受这个答案。 –