欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

flask 发送邮件

最编程 2024-10-09 21:49:23
...

开通邮件IMAP/SMTP服务

以网易邮箱为例

image-20241009164155410

点击开启发送验证后会收到一个密钥,记得保存好

编写代码

安装flask-mail
pip install flask-mail
在config.py文件中配置邮件信息

MAIL_SERVER:邮件服务器

MAIL_USE_SSL:使用SSL

MAIL_PORT:端口

MAIL_USERNAME:用户名

MAIL_PASSWORD:上面获得的密钥

MAIL_DEFAULT_SENDER:默认的发送者

#邮箱配置
MAIL_SERVER = "smtp.163.com"
MAIL_USE_SSL = True
MAIL_PORT = 465
MAIL_USERNAME = "188xxxx5@163.com"
MAIL_PASSWORD = "xxxxxxx"
MAIL_DEFAULT_SENDER = "18xxxxxxx@163.com"
在exts.py创建mail对象
# 这个文件的目的是为了解决循环引用
from flask_mail import Mail

mail = Mail()

在app.py初始化mail
from flask import Flask
import config
from exts import mail
from blueprints.auth import bp as auth_bp

app = Flask(__name__)
app.config.from_object(config)
mail.init_app(app)
app.register_blueprint(auth_bp)



if __name__ == '__main__':
    app.run()

在蓝图下的auth.py文件中编写路由

subject:邮件标题

recipients:接收者

body:邮件内容

from flask import Blueprint
from exts import mail
from flask_mail import Message

bp = Blueprint("auth", __name__, url_prefix="/auth")



@bp.route("/mail/test")
def mail_test():
    message = Message(subject="邮箱测试", recipients=["258xxxxxx9@qq.com"], body="这是一条测试邮件")
    mail.send(message)
    return "邮件发送成功"

测试

image-20241009165108389

打开接收者的邮箱

image-20241009165158947

项目地址

https://gitee.com/yohoo-just-play/liu_oa/