Java教程

flask发送邮件方法

本文主要是介绍flask发送邮件方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

经过一晚上的摸索整理, 测试成功了用163发送邮件

原书代码链接: https://github.com/greyli/helloflask/blob/master/demos/email/app.py

作者博客首页: https://greyli.com/

相比于书中源码, 代码修改如下后运行成功:

import os
from threading import Thread

import sendgrid
from sendgrid.helpers.mail import Email as SGEmail, Content, Mail as SGMail
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Email
from flask import Flask, flash, redirect, url_for, render_template, request


app = Flask(__name__)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

app.config.update(
    # 配置环境变量,可在本文件夹下运行python
    # >>>from app import app
    # >>>app.config
    # 查看配置项内容,字典格式
    SECRET_KEY=os.getenv('SECRET_KEY', 'siec'),
    MAIL_SERVER=os.getenv('MAIL_SERVER', 'smtp.163.com'),
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME=os.getenv('MAIL_USERNAME', 'bob@163.com'),
    MAIL_PASSWORD=os.getenv('MAIL_PASSWORD', 'NOYZJJY'),#此处不输入密码,输入授权码
    MAIL_DEFAULT_SENDER=('注册验证 <bob@163.com>')
)

mail = Mail(app)


# send over SMTP
def send_smtp_mail(subject, to, body):
    message = Message(subject, recipients=[to], body=body)
    mail.send(message)

附:

1.163中设置如下

 

 2.sendgrid当前无法注册

 

这篇关于flask发送邮件方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!