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

相关推荐
c***87198 小时前
Flask:后端框架使用
后端·python·flask
Q_Q5110082859 小时前
python+django/flask的情绪宣泄系统
spring boot·python·pycharm·django·flask·node.js·php
撸码猿9 小时前
《Python AI入门》第9章 让机器读懂文字——NLP基础与情感分析实战
人工智能·python·自然语言处理
二川bro9 小时前
多模态AI开发:Python实现跨模态学习
人工智能·python·学习
2301_764441339 小时前
Python构建输入法应用
开发语言·python·算法
love530love9 小时前
【笔记】ComfUI RIFEInterpolation 节点缺失问题(cupy CUDA 安装)解决方案
人工智能·windows·笔记·python·插件·comfyui
青瓷程序设计9 小时前
昆虫识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
秋邱10 小时前
智启未来:AGI 教育融合 × 跨平台联盟 × 个性化空间,重构教育 AI 新范式开篇:一场 “教育 ×AI” 的范式革命
人工智能·python·重构·推荐算法·agi
爱吃泡芙的小白白10 小时前
vscode、anaconda、git、python配置安装(自用)
ide·git·vscode·python·anaconda·学习记录
谷隐凡二10 小时前
Kubernetes主从架构简单解析:基于Python的模拟实现
python·架构·kubernetes