8

我正在编写一个使用 Python 发送电子邮件的程序。我从各种论坛中学到的是以下代码:

#!/usr/bin/env python
import smtplib
sender = "sachinites@gmail.com"
receivers = ["abhisheks@cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
body = "who cares"
message = "From: " + yourname + "\n" 
message = message + "To: " + recvname + "\n"
message = message + "Subject: " + sub + "\n" 
message = message + body
try:
    print "Sending email to " + recvname + "...",
    server = smtplib.SMTP('smtp.gmail.com:587')
    username = 'XYZ@gmail.com'  
    password = '*****'  
    server.ehlo()
    server.starttls()  
    server.login(username,password)  
    server.sendmail(sender, receivers, message)         
    server.quit()
    print "successfully sent!"
except  Exception:
    print "Error: unable to send email"

但它只是打印“错误:无法发送电子邮件”并在终端上退出。我该如何解决这个问题?

我将最后两行修改为

except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

我收到以下错误消息:

Traceback (most recent call last):
  File "./2.py", line 45, in <module>
    smtpObj = smtplib.SMTP('localhost')
  File "/usr/lib/python2.6/smtplib.py", line 239, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.6/smtplib.py", line 295, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/usr/lib/python2.6/socket.py", line 514, in create_connection
    raise error, msg
socket.error: [Errno 111] Connection refused
4

3 回答 3

16

如果消息头、有效负载包含非 ascii 字符,那么它们应该被编码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header    import Header
from email.mime.text import MIMEText
from getpass         import getpass
from smtplib         import SMTP_SSL


login, password = 'user@gmail.com', getpass('Gmail password:')
recipients = [login]

# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ", ".join(recipients)

# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
    s.login(login, password)
    s.sendmail(msg['From'], recipients, msg.as_string())
finally:
    s.quit()
于 2012-02-14T09:22:40.563 回答
6

如果您打印错误消息,您可能会得到发生错误的全面描述。试试(没有双关语)这个:

try:
    # ...
except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

如果在阅读错误消息后,您仍然不明白您的错误,请使用错误消息更新您的问题,我们可以为您提供更多帮助。


附加信息后更新

错误信息

socket.error: [Errno 111] 连接被拒绝

表示远程端(例如 GMail SMTP 服务器)拒绝网络连接。如果您查看smtplib.SMTP 构造函数,您似乎应该更改

server = smtplib.SMTP('smtp.gmail.com:587')

到以下。

server = smtplib.SMTP(host='smtp.gmail.com', port=587)
于 2012-02-14T05:45:38.073 回答
0

根据错误信息,您使用 localhost 作为 SMTP 服务器,然后连接被拒绝。我猜您的本地主机没有运行 SMTP 服务器,您需要确保您连接的 SMTP 服务器有效。

于 2012-02-14T06:15:04.943 回答