flask_mail是一个轻量级的 Flask 扩展,用于在 Flask 应用中实现邮件发送功能。它集成了 Python 标准库中的 smtplibemail.mime 模块,使邮件发送更加简单高效。接下来我来介绍如何在代码中使用它。

以下适用于比较标准的项目格式,如果想要快速一点(看看效果),直接跳到一个文件

用到项目里

目录结构

1
2
3
4
5
6
7
8
9
10
my_flask_api/
├── App/
│ ├── __init__.py # 应用初始化
│ ├── routes/ # 放各种接口
│ │ └── api.py # 业务逻辑
│ ├── exts.py #这个文件存在的目的是为了解决循环引用
│ │
│ ├── func.py #自己定义的函数
│ └── config.py # 配置文件
└── app.py # 启动入口

init.py

这个就不说了,前面flask接口搭建有说过

1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import Flask
from .exts import *
from .config import config
from .routes.api import api


def create_app():
app=Flask(__name__)
app.config.from_object(config)
mail.init_app(app)
app.register_blueprint(api)

return app

如果在写项目的时候,可以按照这个目录结构去编写,exts.py这个文件用于解决循环引用的问题,就比方说我现在要用flask_mail在不同的api下发送邮件,那么我需要在不同的文件分别引入flask_mail,那假设我还需要操作数据库,那我是不是又要再引入flask_sqlalchemy呢。我们在exts文件内分别创建实例,需要用的时候直接导出就可以了。

exts.py

1
2
3
4
5

#这个文件存在的目的是为了解决循环引用
from flask_mail import Mail
mail = Mail()#创建一个邮箱实例

config.py

在使用邮箱的时候,我们需要获取邮箱的一些配置,这里列举如下:

常用的配置项

MAIL_SERVER:邮件服务器地址,默认是 ‘localhost’,表示本地服务器。如果你用的是第三方邮件服务(如 Gmail),需要改成对应的 SMTP 地址。

MAIL_PORT:邮件服务器端口,默认是 25,这是 SMTP 的标准端口。如果用 SSL/TLS,可能需要改成 465 或 587。

MAIL_USE_TLS:是否启用 TLS(传输层安全协议),默认是 False。如果你的邮件服务器要求加密连接,可以设为 True。

MAIL_USE_SSL:是否启用 SSL(安全套接层协议),默认是 False。TLS 和 SSL 只能选一个,通常用 TLS(更安全)。

MAIL_USERNAME:邮件服务器的用户名,默认是 None。如果服务器需要身份验证,需要填写你的邮箱账号。

MAIL_PASSWORD:邮件服务器的密码,默认是 None。配合用户名使用,进行身份验证。

MAIL_DEFAULT_SENDER:默认发件人地址,默认是 None。如果不设置,每次发送邮件都要指定发件人。

MAIL_MAX_EMAILS:一次连接最多发送的邮件数,默认是 None(无限制)。可以用来限制批量发送邮件的数量。

首先我们需要有一个邮箱账号,我这里就拿QQ邮箱做例子,我们需要进入到QQ邮箱然后点击右上角自己的账号

选择账号与安全,然后选择安全设置,然后点击生成授权码

复制授权码,在config.py文件内

1
2
3
4
5
6
7
class config:
MAIL_SERVER='smtp.qq.com'
MAIL_USE_TLS=True
MAIL_PORT=587
MAIL_USERNAME='你的qq邮箱'
MAIL_PASSWORD='你获取到的授权码'
MAIL_DEFAULT_SENDER=('自定义用户名','和MAIL_USERNAME要一样')

func.py

平常自己封装一些函数写在这里面,写上注释方便维护,邮件支持同时发送到多个邮箱

自己定义的函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# 可以在这个文件内定义一些需要使用的函数,方便调用
from flask_mail import Message
from .exts import mail
import random
def send_code(email):
code=''.join(str(random.randint(0, 9)) for _ in range(6))
msg=Message("胡摆摆邮箱验证码",recipients=[email])
msg.html='''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>邮箱验证码</title>
<style>
/* 全局样式 */
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.5;
color: #333;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
/* 邮件容器 - 响应式核心 */
.email-container {
max-width: 600px;
margin: 20px auto;
padding: 0;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
/* 头部 */
.header {
background-color: #4285f4;
color: white;
padding: 20px;
text-align: center;
}
.header h1 {
margin: 0;
font-size: 24px;
}
/* 内容区域 */
.content {
padding: 30px;
background-color: #fff;
}
.greeting {
font-weight: bold;
margin-bottom: 20px;
}
/* 验证码样式 - 响应式关键 */
.verification-code {
font-size: 28px;
letter-spacing: 8px;
color: #4285f4;
text-align: center;
margin: 30px 0;
font-weight: bold;
background-color: #f0f4ff;
padding: 15px;
border-radius: 4px;
display: inline-block;
width: auto;
min-width: 200px;
}
/* 按钮样式 - 响应式关键 */
.action-button {
display: inline-block;
padding: 12px 24px;
background-color: #4285f4;
color: white !important;
text-decoration: none;
border-radius: 4px;
margin: 20px 0;
font-weight: bold;
text-align: center;
}
/* 页脚 */
.footer {
text-align: center;
font-size: 12px;
color: #999;
padding: 15px;
background-color: #fafafa;
border-top: 1px solid #eee;
}
/* 移动端优化 */
@media screen and (max-width: 480px) {
.email-container {
margin: 10px;
border-radius: 0;
}
.header {
padding: 15px;
}
.header h1 {
font-size: 20px;
}
.content {
padding: 20px;
}
.verification-code {
font-size: 24px;
letter-spacing: 6px;
padding: 12px;
min-width: 180px;
}
.action-button {
display: block;
padding: 15px;
}
}
</style>
</head>
'''+f'''
<body>
<!-- 邮件主体 -->
<table class="email-container" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="header">
<h1>您的验证码</h1>
</td>
</tr>
<tr>
<td class="content">
<p class="greeting">尊敬的用户,您好!</p>
<p>您正在进行邮箱验证,以下是您的验证码:</p>

<!-- 验证码 -->
<div class="verification-code">{code}</div>

<p>请在 <strong>10分钟内</strong> 完成验证,切勿将验证码透露给他人。</p>
<p>如果这不是您本人操作,请忽略此邮件。</p>

<!-- 操作按钮 -->
<a href="https://www.xhwv.cn" class="action-button">立即验证</a>
</td>
</tr>
<tr>
<td class="footer">
<p>© 2025 胡摆摆. 保留所有权利.</p>
<p>此邮件为系统自动发送,请勿直接回复。</p>
</td>
</tr>
</table>
</body>
</html>
'''
mail.send(msg)

api.py

定义发送邮箱验证码的接口,调用函数,传入目的地邮箱,后续可以加入一些radis或者是数据库操作,存储验证码方便验证。

1
2
3
4
5
6
7
8
from flask import Blueprint
from ..func import send_code
api=Blueprint('api',__name__,url_prefix="/")

@api.route("/send_code")
def send_email():
send_code("211941596@qq.com")
return {"code":200,"message": "success"}

app.py

1
2
3
4
5
6
from APP import create_app


if __name__ == "__main__":
app = create_app()
app.run(debug=True)

全部写在一个文件里

创建一个app.py,写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
from flask import Flask
from flask_mail import Mail,Message
mail=Mail()
class config:
MAIL_SERVER='smtp.qq.com'
MAIL_USE_TLS=True
MAIL_PORT=587
MAIL_USERNAME='你的qq邮箱'
MAIL_PASSWORD='你获取到的授权码'
MAIL_DEFAULT_SENDER=('自定义用户名','和MAIL_USERNAME要一样')
app = Flask(__name__)
app.config.from_object(config)
mail.init_app(app)

@app.route("/send_code")
def index():
msg=Message("胡摆摆邮箱验证码",recipients=["211941596@qq.com"])
msg.html='''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>邮箱验证码</title>
<style>
/* 全局样式 */
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.5;
color: #333;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
/* 邮件容器 - 响应式核心 */
.email-container {
max-width: 600px;
margin: 20px auto;
padding: 0;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
/* 头部 */
.header {
background-color: #4285f4;
color: white;
padding: 20px;
text-align: center;
}
.header h1 {
margin: 0;
font-size: 24px;
}
/* 内容区域 */
.content {
padding: 30px;
background-color: #fff;
}
.greeting {
font-weight: bold;
margin-bottom: 20px;
}
/* 验证码样式 - 响应式关键 */
.verification-code {
font-size: 28px;
letter-spacing: 8px;
color: #4285f4;
text-align: center;
margin: 30px 0;
font-weight: bold;
background-color: #f0f4ff;
padding: 15px;
border-radius: 4px;
display: inline-block;
width: auto;
min-width: 200px;
}
/* 按钮样式 - 响应式关键 */
.action-button {
display: inline-block;
padding: 12px 24px;
background-color: #4285f4;
color: white !important;
text-decoration: none;
border-radius: 4px;
margin: 20px 0;
font-weight: bold;
text-align: center;
}
/* 页脚 */
.footer {
text-align: center;
font-size: 12px;
color: #999;
padding: 15px;
background-color: #fafafa;
border-top: 1px solid #eee;
}
/* 移动端优化 */
@media screen and (max-width: 480px) {
.email-container {
margin: 10px;
border-radius: 0;
}
.header {
padding: 15px;
}
.header h1 {
font-size: 20px;
}
.content {
padding: 20px;
}
.verification-code {
font-size: 24px;
letter-spacing: 6px;
padding: 12px;
min-width: 180px;
}
.action-button {
display: block;
padding: 15px;
}
}
</style>
</head>
<body>
<!-- 邮件主体 -->
<table class="email-container" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td class="header">
<h1>您的验证码</h1>
</td>
</tr>
<tr>
<td class="content">
<p class="greeting">尊敬的用户,您好!</p>
<p>您正在进行邮箱验证,以下是您的验证码:</p>

<!-- 验证码 -->
<div class="verification-code">8 6 4 2</div>

<p>请在 <strong>10分钟内</strong> 完成验证,切勿将验证码透露给他人。</p>
<p>如果这不是您本人操作,请忽略此邮件。</p>

<!-- 操作按钮 -->
<a href="https://www.xhwv.cn" class="action-button">立即验证</a>
</td>
</tr>
<tr>
<td class="footer">
<p>© 2025 胡摆摆. 保留所有权利.</p>
<p>此邮件为系统自动发送,请勿直接回复。</p>
</td>
</tr>
</table>
</body>
</html>
'''
mail.send(msg)
return {
"code":200,
"message":"success"
}





if __name__ == "__main__":
app.run(debug=True)

然后就可以运行app.py,访问http://127.0.0.1:5000/send_code

接口返回200,成功收到验证码

收到验证码了,下课!!!

参考文件

Flask Mail中文文档