Python发送QQ邮件

使用Python的smtplib可以发送QQ邮件,代码如下

python 复制代码
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header


sender = '111@qq.com'  # 发送邮箱
receivers = ['222@qq.com']  # 接收邮箱
auth_code = "abc"  # 授权码

message = MIMEText('Python发送邮件', 'plain', 'utf-8')
message['From'] = Header("Sender<%s>" % sender)  # 发送者
message['To'] = Header("Receiver<%s>" % receivers[0])  # 接收者

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    server = smtplib.SMTP_SSL('smtp.qq.com', 465)
    server.login(sender, auth_code)
    server.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    server.close()
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发送邮件服务器要用465端口,否则如下错误:

login的密码不是邮箱登录密码,而是授权码,需要在QQ邮箱设置-账号里获取。

否则会报如下错误:

python 复制代码
SMTPServerDisconnected: Connection unexpectedly closed
python 复制代码
SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1002)

发送消息的From和To要用标准格式,否则报错:

python 复制代码
SMTPDataError: (550, b'The "From" header is missing or invalid. Please follow RFC5322, RFC2047, RFC822 standard protocol. https://service.mail.qq.com/detail/124/995.')

参考

https://wx.mail.qq.com/list/readtemplate?name=app_intro.html#/agreement/authorizationCode
https://help.mail.qq.com/detail/0/994
https://docs.python.org/zh-cn/3/library/netdata.html
https://docs.python.org/zh-cn/3/library/smtplib.html

相关推荐
User:你的影子1 分钟前
WPF ItemsControl 绑定
开发语言·前端·javascript
guidovans12 分钟前
Crawl4AI精准提取结构化数据
人工智能·python·tensorflow
longerxin202018 分钟前
MongoDB 在线安装-一键安装脚本(CentOS 7.9)
数据库·mongodb·centos
野生的编程萌新30 分钟前
【C++深学日志】从0开始的C++生活
c语言·开发语言·c++·算法
水无痕simon33 分钟前
3 水平分表
java·数据库
恣艺40 分钟前
探索数据库世界:从基础类型到实际应用
数据库
言之。1 小时前
Django REST Framework响应类Response详解
后端·python·django
※※冰馨※※1 小时前
【c#】 使用winform如何将一个船的图标(ship.png)添加到资源文件
开发语言·windows·c#
小钻风33661 小时前
IDEA连接redis数据库时出现Failed to connect to any host resolved for DNS name.
数据库
Abadbeginning1 小时前
FastSoyAdmin centos7云服务器+宝塔部署
vue.js·后端·python