python 使用 QQ 邮箱实现发送邮件功能

2025-08-18 18:43:36

邮箱授权

使用 QQ 邮箱实现发送邮件功能,QQ 邮箱需要先确认我们的身份(这个 QQ 号是我的,不是别人的)

QQ 邮箱不允许直接使用密码登录客户端,所以需要先获取授权码。

进入 QQ 邮箱,点击设置 > 账户。

往下拉找到如下内容,点击开启或生成授权码。

发送邮件

封装发送邮件的方法。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(
    authorization, 
    sender, 
    receive, 
    title, 
    content,
    content_type = 'plain',
    host = 'smtp.qq.com', 
    port = 465,
):
    msg = MIMEMultipart()
    msg.attach(MIMEText(content, content_type, 'utf-8'))
    msg['Subject'] = title
    msg['From'] = sender
    
    s = smtplib.SMTP_SSL(host, port)
    s.login(sender, authorization)
    s.sendmail(sender, receive, msg.as_string())

发送纯文本邮件

send_email(
    authorization='你的邮箱授权码',
    sender='你的发件人邮箱',
    receive='你的收件人邮箱, 多个邮箱使用逗号隔开',
    title='测试python发邮件',
    content='Hello world',
)

print('邮件发送成功')

发送 html 邮件

send_email(
    authorization='你的邮箱授权码',
    sender='你的发件人邮箱',
    receive='你的收件人邮箱, 多个邮箱使用逗号隔开',
    title='测试python发邮件',
    content='<h1 style="color: red;">Hello World</h1>',
    # 需要指定邮件内容类型为 html
    content_type='html',
)

print('邮件发送成功')

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: