以前也试过模拟发Email,但好像都忘了,于是按照菜鸟教程的smtplib方法重新试了一下:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = 'from@runoob.com'
receivers = ['<username>@qq.com'] # 接收邮件,可设置为你的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: 无法发送邮件"
结果疯狂报错,说是什么ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接.
这个问题查搜索引擎发现都是说什么网络连接问题(比如防火墙、局域网等等),但其实不是关键问题,主要是这个代码有点问题。
修正后的代码是这样的:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
f = open('./config.txt', 'r')
# \n换行符需要删掉
sender = f.readline()[:-1]
receiver = f.readline()[:-1]
password = f.readline()[:-1]
f.close()
receivers = [receiver]
message = MIMEText('Python骚扰邮件', 'plain', 'utf-8')
message['From'] = Header("Python骚扰邮件", 'utf-8')
message['To'] = Header("Python骚扰邮件", 'utf-8')
subject = 'Python-SMTP邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
smtpObj.connect("smtp.qq.com", 465)
smtpObj.login(sender, password)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
做几点必要说明:
- 个人信息存在文件里是比较妥善的做法,通过读文件来获取信息
- 读的一行文件带有换行符,需要去掉末尾
\n
- 发QQ邮箱需要开启SMTP服务并获取授权码
- 注意异常处理,其实这里的异常处理比较暴力,真的出错也不便于排错