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

相关推荐
2301_8213696114 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
m0_5613596718 分钟前
使用Kivy开发跨平台的移动应用
jvm·数据库·python
编程火箭车43 分钟前
04.第一个 Python 程序:Hello World 从编写到运行全解析
python·python第一个程序·python入门报错解决·python新手教程·hello world 程序·python终端运行·pycharm运行代码
qq_423233901 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
疯狂踩坑人1 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
HDO清风2 小时前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
weixin_499771552 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
weixin_452159552 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
多米Domi0112 小时前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
深蓝海拓2 小时前
PySide6从0开始学习的笔记(二十六) 重写Qt窗口对象的事件(QEvent)处理方法
笔记·python·qt·学习·pyqt