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

相关推荐
圆圆讲门店几秒前
挑选同城获客服务机构时需要考量的核心因素都有哪些?
大数据·网络·人工智能·python
lie..15 分钟前
30天从零开始学AI应用开发(Day 12):像产品一样稳:流式输出、报错重试、花钱控制
开发语言·人工智能·php
傻啦嘿哟19 分钟前
Python的默认参数把我坑惨了,原来写[]和写None的区别这么大
开发语言·python·机器学习
微小冷21 分钟前
Python凸优化cvxpy初步
python·机器人·凸优化·数学规划·cvxpy
在世修行36 分钟前
干货:显式映射 vs 自动判据
python·插件
xzal1240 分钟前
Python之简单理解栈和队列
python
DeepAgent1 小时前
AI Agent 工程实践(49):一次真实优化——从 Agent v1 到 v2
开发语言·人工智能·agent
知识分享小能手1 小时前
C++ 学习教程,从入门到精通,C++对象和类 — 详细知识点总结(10)
开发语言·c++·学习
lupai1 小时前
维修保养记录精准版 API 对接实战指南
数据库·python
郑州光合科技余经理1 小时前
同城电商系统:库存变更怎么同步到订单
java·开发语言·前端·后端·uni-app·php·ai编程