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

相关推荐
兵慌码乱5 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei8 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0014 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn15 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏