代码如下:
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')
message['To'] = Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print ("邮件发送成功")
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
报错如下:
E:\pythonwork\venv\Scripts\python.exe E:/pythonwork/day6/EmailTest.py
Traceback (most recent call last):
File "E:/pythonwork/day6/EmailTest.py", line 19, in <module>
smtpObj = smtplib.SMTP('localhost')
File "D:\Python\Python36\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "D:\Python\Python36\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "D:\Python\Python36\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "D:\Python\Python36\lib\socket.py", line 724, in create_connection
raise err
File "D:\Python\Python36\lib\socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接
是不是因为没有安装sendmail的问题,望大神能给与解决