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

相关推荐
yangshicong1 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华1 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72881 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment3 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
互联网中的一颗神经元4 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql
RSTJ_16255 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND EIGHTEEN
python
开源量化GO5 小时前
近期量化学习路径,交易理解和技术实现要接上
人工智能·python
c_lb72886 小时前
近期手工规则量化,学习表达到开发验证要连起来
人工智能·python
tkevinjd6 小时前
MiniCode 项目详解7:Memory 记忆系统
大数据·python·搜索引擎·llm·agent
郭老二6 小时前
【Python】Web框架 FastAPI 详解
python·fastapi