我想用Python发送电子邮件。下面是一个示例代码:
#!/usr/bin/python
import smtplib
sender = 'test@gmail.com'
receivers = ['test@gmail.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print("Send OK.")
except SMTPException:
print("Send NOT OK.")
当我尝试运行此程序时,我遇到了一些错误:
Traceback (most recent call last):
File ".\sendEmail.py", line 16, in <module>
smtpObj = smtplib.SMTP('localhost')
File "C:\Python34\lib\smtplib.py", line 242,
(code, msg) = self.connect(host, port)
File "C:\Python34\lib\smtplib.py", line 321,
self.sock = self._get_socket(host, port, se
File "C:\Python34\lib\smtplib.py", line 292,
self.source_address)
File "C:\Python34\lib\socket.py", line 509, i
raise err
File "C:\Python34\lib\socket.py", line 500, i
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Nie mo
During handling of the above exception, another
Traceback (most recent call last):
File ".\sendEmail.py", line 19, in <module>
except SMTPException:
NameError: name 'SMTPException' is not defined
如何改进此代码以发送电子邮件?感谢。
答案 0 :(得分:1)
看看这一行:
smtpObj = smtplib.SMTP('localhost')
您正在尝试连接到localhost - 您自己的计算机。你有运行SMTP服务器吗?我不这么认为。
配置正确的SMTP服务器。您可以使用您的个人电子邮件帐户。