Flask-mail can connect to the SMTP server in the configuration to send mail, if the SMTP server is not configured, will be connected to localhost by default
I. Configuration and initialization
(1) Flask application Configuration
#configuration OptionsMail_server ='smtp.qq.com' #Mail ServerMail_port = 25#PortMail_use_tls = False#Transport Layer Security protocolMail_use_ssl = False#Secure Sockets Layer protocolMail_username =' You' #Account NumberMail_password ='Your-password'#Password
(2) initialization
from Import Mail from Import = Flask (__name__= Mail (APP)
Two. Send mail
fromFlask.ext.mailImportMessage fromAppImportMail#Create a messagemsg = Message ("Message Subject", Sender='[email protected]', Recipients=['[email protected]','[email protected]']) Msg.body='text content'msg.html='<b>html Content </b>'#Send message, flask-mail need to send mail in current_app contextWith App.app_context (): Mail.send (msg)
Auxiliary Mail Send function
defSend_email (To, subject, template, * *Kwargs): App=current_app._get_current_object () msg=Message (subject, Sender='[email protected]', Recipients=[to]) Msg.body= Render_template (template +'. txt', **Kwargs) msg.html= Render_template (template +'. html', **Kwargs)#send a message in a new threadTHR = Thread (Target=send_async_mail, args=[App, MSG]) Thr.start ()returnTHR#send messages asynchronously and speed updefSend_async_mail (App, msg): With App.app_context (): Mail.send (msg)
The Flask-mail of Flask learning record