使用 Python 发送电子邮件通过 QQ 邮箱

简介

本文介绍如何使用 Python 的 smtplibemail 库通过 QQ 邮箱发送电子邮件。

准备工作

  1. 安装必要的 Python 库:

    bash 复制代码
    pip install secure-smtplib
  2. 获取 QQ 邮箱的 SMTP 授权码。你需要登录到 QQ 邮箱,然后进入设置,找到 SMTP 服务设置,并生成授权码。

示例代码

下面是一个简单的 Python 示例代码:

python 复制代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# QQ 邮箱 SMTP 服务器地址
smtp_server = 'smtp.qq.com'
smtp_port = 465  # SSL 端口号

# 发件人和收件人邮箱
sender = 'your_email@qq.com'
receiver = 'receiver_email@example.com'

# QQ 邮箱 SMTP 授权码
password = 'your_authorization_code'

# 邮件内容
subject = 'Hello, this is a test email'
content = 'This is a test email sent from Python.'

# 创建 MIMEText 对象
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = Header(sender)
msg['To'] = Header(receiver)
msg['Subject'] = Header(subject)

# 发送邮件
try:
    server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.login(sender, password)
    server.sendmail(sender, [receiver], msg.as_string())
    print('Email sent successfully.')
except Exception as e:
    print(f'Failed to send email: {e}')
finally:
    server.quit()

运行代码

保存上面的代码到一个 Python 文件,然后运行它。如果一切设置正确,你应该能成功发送电子邮件。


这样,你就可以使用 Python 通过 QQ 邮箱发送电子邮件了。希望这篇文章能帮助你!

相关推荐
呆萌很几秒前
字典推导式练习题
python
闲人编程31 分钟前
Python在云计算中的应用:AWS Lambda函数实战
服务器·python·云计算·aws·lambda·毕设·codecapsule
小兔崽子去哪了42 分钟前
Python 数据分析环境搭建与工具使用指南
python
不惑_1 小时前
Java 使用 FileOutputStream 写 Excel 文件不落盘?
开发语言·python
IT小哥哥呀1 小时前
Python实用技巧:批量处理Excel数据并生成销售报表(含实战案例)
python·pandas·数据可视化·数据处理·报表生成·excel自动化·办公神器
烤奶要加冰2 小时前
PyCharm 社区版全平台安装指南
ide·windows·python·pycharm·mac
Siren_dream2 小时前
anaconda与pycharm
ide·python·pycharm
whale fall2 小时前
Windows下PyCharm如何激活python的虚拟环境
ide·python·pycharm
Geo_V2 小时前
提示词工程
人工智能·python·算法·ai
B站_计算机毕业设计之家2 小时前
计算机视觉:python车辆行人检测与跟踪系统 YOLO模型 SORT算法 PyQt5界面 目标检测+目标跟踪 深度学习 计算机✅
人工智能·python·深度学习·算法·yolo·目标检测·机器学习