使用 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 邮箱发送电子邮件了。希望这篇文章能帮助你!

相关推荐
啊森要自信16 分钟前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
赵谨言27 分钟前
基于python智能家居环境质量分析系统的设计与实现
开发语言·经验分享·python·智能家居
程序员三藏1 小时前
银行测试:第三方支付平台业务流,功能/性能/安全测试方法
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·安全性测试
程序员晚枫1 小时前
Python版本进化史:从3.6到3.14,每个版本都带来了什么惊喜?
python
程序猿小D1 小时前
【完整源码+数据集+部署教程】 【零售和消费品&存货】【无人零售】自动售卖机饮料检测系统源码&数据集全套:改进yolo11-KernelWarehouse
python·yolo·计算机视觉·目标跟踪·数据集·yolo11·自动售卖机饮料检测系统
寒怜z1 小时前
python 景区游客量统计
python
程序员晚枫2 小时前
Python 3.14发布:多解释器让性能飙升300%,GIL时代即将终结!
python
程序猿小D2 小时前
【完整源码+数据集+部署教程】 【零售和消费品&存货】条形码检测系统源码&数据集全套:改进yolo11-TADDH
python·yolo·计算机视觉·目标跟踪·数据集·yolo11·条形码检测系统
废弃的小码农2 小时前
测试基础--Day01--软件测试基础理论
python·功能测试·测试工具
火白学安全2 小时前
《Python红队攻防脚本零基础编写:入门篇(一)》
python·安全·web安全·网络安全·系统安全