Flask邮件发送

​ 应用场景:
用户在登记或然密码丢失等进程中,账号绑定邮箱,用户在开始展览身份认证的历程中,电子邮箱确实是一种很常用的情势,Python中提供了smtplib可以完毕出殡和埋葬电子邮件作用,Flask框架也许有相应的flask-email库,扩张对电子发送的支撑

壹、Flask通过flask-mail插件扶助邮件发送
pip install flask-mail
pip install flask-script

安装

二、下述将从二种格局验证flask-mail发送邮件,一种是本子实施,另壹种是合2为1在行使(程序)中发送邮件

pip3 install flask-mail

2.一脚本办法,emails.py

导入及初叶化

from flask import Flask

from flask_mail import Message,Mail

from flask_script import Manager,Shell

import os

app=Flask( __name__)

manager=Manager(app)

mail=Mail(app)

app.config['MAIL_SERVER']="smtp.163.com"  #各个邮件服务商MAIL_SERVER不同

app.config['MAIL_PORT']=465

app.config['MAIL_USE_SSL']=True

app.config['MAIL_USERNAME']=os.environ.get("MAIL_USERNAME")

app.config['MAIL_PASSWORD']=os.environ.get("MAIL_PASSWORD")

(flask-venv) $export MAIL_USERNAME="gyc1412@163.com"

(flask-venv) $export MAIL_PASSWORD="xxxxxxx"

python emails.py shell

>>>from flask_mail import Message

>>>from emails import mail

>>>msg=Message("test subject",sender="gyc1412@163.com",

recipients=['guangyichen@sina.cn'])    

>>>msg.body="text body"

>>>msg.html='<b>HTML</b>body'

>>>with app.app_context():

...    mail.send(msg)

...

>>>
from flask_mail import Mail
mail=Mail(app)

2.二 邮件发送集成到利用的方法,个中使用了四线程本领(threading)

Flask-mail能够接连SMTP服务器,并把邮件选取那一个服务器发送出去.
Flask-mail服务器相关配置参数:

#encoding=utf-8

from flask import Flask,render_template

from flask_mail import Message,Mailfrom threading 

import Threadfrom flask_script import Manager,Shell

import os app=Flask(__name__)

app.config['MAIL_SERVER']='smtp.163.com'

app.config['MAIL_PORT']=465

app.config['MAIL_USE_TLS']=False

app.config['MAIL_USE_SSL']=True

app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')

app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')

mail=Mail(app)manager=Manager(app)

def send_async_email(app,msg):    

    with app.app_context():              #激活上下文?        

        mail.send(msg)                   

@app.route('/')

def index():    

    msg=Message('主题',sender=os.environ.get('MAIL_USERNAME'),

recipients=['guangyichan@gmail.com'])                       

    msg.body="文本body"    

    msg.html='<b>HTML</b>body'    

    thread=Thread(target=send_async_email,args=[app,msg])          

    thread.start()    

    mail.send(msg)    

    return '异步邮件发送成功。'

if __name__  ==  '__main__': 

    manager.run()
参数 默认值 说明
MAIL_SERVER loaclhost SMTP服务器主机或者IP地址
MAIL_PORT 25 电子邮件服务器端口
MAIL_USE_TLS False 是否启用传输层安全协议(TLS)
MAIL_USE_SSL False 是否启用安全套接层协议(SSL)
MAIL_USERNAME None 电子邮箱账号用户名
MAIL_PASSWORD None 电子邮箱账号密码
MAIL_DEBUG False 是否启动调试

运营:python emails.py runserver -h 0.0.0.0 -p9090 页面刷新就能够发送邮件

一般在安插文件config配置如下

#方式1在config文件中配置
MAIL_SERVER='smtp.163.com'
MAIL_PORT=25
MAIL_USE_TLS=True
MAIL_USERNAME='***@163.com'
MAIL_PASSWORD='******'
MAIL_DEBUG=True

#方式2 在app中配置
app.config["MAIL_SERVER"] = "smtp.163.com"
app.config["MAIL_PORT"] = 25
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = "xxxxx@163.com"
app.config["MAIL_PASSWORD"] = "123456"

#方式3 在app中直接配置config
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER','smtp.1000phone.com')
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME','xialigang@1000phone.com')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD','123456')
# os.environ.get('环境变量名','环境变量值'),将获取的环境变量绑定到config文件

协助进行邮件发送

from flask import Flask, render_template_string
from flask_mail import Mail, Message
import os

app = Flask(__name__)

app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER', 'smtp.163.com')
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', '发件人@163.com')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', 'mm22kk11')

# 绑定实例化mail对象
mail = Mail(app)


@app.route('/')
def index():
    msg = Message(subject='邮件激活', recipients=['收件人@qq.com'], sender=app.config['MAIL_USERNAME'])
    msg.html = render_template_string('<h1>大郎,我是金莲啊<h1>')
    mail.send(message=msg)
    return '发送邮件'

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

# sender 发送人邮箱   recipients接收人邮箱
# smtp为发送邮件服务器

注意:

1 subject为邮件标题。 
2 sender为发送方
3 recipients为接收方,可以设置一个或者多个收件人,也可以后续再添加
4 邮件内容可以包含主体body以及/或者 HTML:

msg.recipients = ["xxx@qq.com"]
msg.add_recipient("xxxx@qq.com")

msg.body = "testing"
msg.html = "<b>testing</b>"

5 实例化Message 传参如下
msg = Message(subject="Hello World!",
              sender="from@qq.com",
              recipients=["to@example.com"])

但是那样明显开采有个难题,因为是一起单线程的邮件发送,一旦用户多进入新闻队列,那样响应时间会较长春电电影发行体制片厂响用户体验,由此大家立异下使用异步四线程的款式发送.

异步10二线程发送邮件

from flask import Flask,render_template_string,render_template
from flask_mail import Mail,Message
import os
from threading import Thread

app = Flask(__name__)

app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER','smtp.163.com')

app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME','发件人@163.com')

app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD','mm22kk11')
mail = Mail(app)
#开启异步处理
def async_send_mail(app,msg):
    #获取当前程序的上下文
    with app.app_context():
        #邮件发送
        mail.send(message=msg)


def send_mail(subject,to,tem,**kwargs):
    #实例化的message对象(subject,recipients,sender)
    msg = Message(subject=subject, recipients=[to], sender=app.config['MAIL_USERNAME'])
    #重定向到mail.html
    msg.html = render_template(tem+'.html',**kwargs)
    #thread代表发送邮件的线程信息
    thread = Thread(target=async_send_mail,args=(app,msg))
    thread.start()

@app.route('/')
def index():
    send_mail('邮件激活','收件人@qq.com','mail',username='zhangsan')
    return '发送邮件'

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

#mail.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>邮件信息</title>
</head>
<body>
    {{ username }},金莲我来了!!
</body>
</html>

如上正是翻开的二拾三十二线程异步发送邮件,能够管理多量的邮件请求,减弱用户的等候时间.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图