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

相关推荐
工会代表34 分钟前
使用 GitHub Actions 与 Docker 实现 CaptchaVision API 持续集成
python
cvyoutian42 分钟前
解决 PyTorch 大型 wheel 下载慢、超时和反复重下的问题
人工智能·pytorch·python
小徐敲java1 小时前
python的FastAPI框架
开发语言·python·fastapi
CHANG_THE_WORLD2 小时前
Python 切片操作全面解析
开发语言·python
是一个Bug2 小时前
Spring事件监听器在电商订单系统中的应用
java·python·spring
shangjian0072 小时前
Python基础-闭包和装饰器
开发语言·python
三维空间2 小时前
如何在Python多进程中避免死锁问题?
python
冤大头编程之路2 小时前
Python并发编程实操教程:多线程/多进程/异步全解析
python
dhdjjsjs2 小时前
Day30 Python Study
开发语言·前端·python
Eric.Lee20213 小时前
mujoco构建无物理约束的几何体运动
python·物理引擎·mujoco·物理模型仿真