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

相关推荐
必须会一定会3 小时前
Agent Plugins 1.0实战:plugin.json、skills、mcp.json目录结构与迁移
开发语言·人工智能·ai编程
St_rive3 小时前
Page Object设计模式
java·开发语言·设计模式
CTA量化套保3 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
wp123_13 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记
wuyk5553 小时前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
清水白石0084 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
杨运交4 小时前
[060][调度模块]Redisson vs Redis 原生锁:两种分布式锁实现深度对比
数据库·redis·分布式
FungLeo4 小时前
Node 后端实战 · 列表查询到底怎么写?一个通用 DSL 封装,过滤分页排序一次搞定
数据库·node.js·serverless·dsl 封装·通用列表查询
Elias不吃糖4 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
luj_17684 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法