你好,游客 登录 注册 搜索
背景:
阅读新闻

Flask-mail扩展的基本使用

[日期:2014-07-26] 来源:Linux社区  作者:forlinux [字体: ]

1.安装

pip install flask-mail

2.使用

    1.配置一些发送邮件的参数例如邮件发送服务器的地址,端口,是否加密等。

    2.初始化flask-mail插件。

    3.创建Message实例,设置发送的内容,地址和主题等信息

    4.使用Mail实例针对Message的实例来发送

3.配置参数详解

下面这是在使用mail的时候需要指定的一些配置参数,需要在使用mail之前来设置相关的参数。

MAIL_HOSTNAME  localhost    Hostname or IP address of the email server

MAIL_PORT      25            Port of the email server

MAIL_USE_TLS  False Enable  Transport Layer Security (TLS) security

MAIL_USE_SSL  False Enable  Secure Sockets Layer (SSL) security

MAIL_USERNAME  None            Mail account username

MAIL_PASSWORD  None            Mail account passwor


4.初始化

和绝大多数的Flask插件一样,要使用Flask插件的时候需要对插件进行初始化,大都数插件的初始化方式经过Flask封装后变的统一了,大部分情况下都是想如下方式来进行初始化。其中app是Flask应用的实例。

from flask.ext.mail import Mail

mail = Mail(app)

5.发送邮件

初始化好Mail插件后就生成了一个mail的实例,接下来就需要创建一个Message的实例这里面包含了要发送的邮件的所有信息,例如邮件发送的地址,邮件的主题,邮件的内容,邮件的html模板等。

from flask.ext.mail import Message

def send_email():

    msg = Message("邮件的subject",sender="localhost", recipients=["445188382@qq.com"])

    msg.body = "邮件的主题内容"

    msg.html = "<h1>邮件的html模板<h1> body"

    #发送邮件

    mail.send(msg)


msg.html = "<h1>邮件的html模板<h1> body" 这里的body是一个占位符将会替换msg.body里面的内容。

发面的邮件发送过程是同步的,当点击发送邮件的时候页面会卡住好几秒直到邮件发送完毕。

6.异步发送邮件

这里通过线程的方式来实现邮件发送,主进程继续完成页面的输出的。从而达到异步的效果。

from threading import Thread

def send_async_email(app, msg):

    with app.app_context():

        mail.send(msg)

def send_email():

    msg = Message("邮件的subject",sender="localhost", recipients=["445188382@qq.com"])

    msg.body = "邮件的主题内容"

    msg.html = "<h1>邮件的html模板<h1> body"

    #发送邮件

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

    thr.start()

    return "OK"

许多Flask的扩展都是假定自己运行在一个活动的应用和请求上下文中,Flask-Mail的send函数使用到current_app这个上下文了,所以当mail.send()函数在一个线程中执行的时候需要人为的创建一个上下文,所有在send_async_email中使用了app.app_context()来创建一个上下文。

原文如下:

Many Flask extensions operate
under the assumption that there are active application and request contexts. Flask-Mail’s
send() function uses current_app, so it requires the application context to be active.
But when the mail.send() function executes in a different thread, the application context
needs to be created artificially using app.app_context().

7.完整实例

下面是一个完整的简单异步发送邮件的实例:

from flask import Flask

from flask import current_app

from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config.from_object(__name__)

db = SQLAlchemy(app)

from flask.ext.mail import Mail

from flask.ext.mail import Message

from threading import Thread

mail = Mail(app)

app.config['MAIL_SERVER']='localhost'

app.config['MAIL_PORT']=25

def send_async_email(app,msg):

        with app.app_context():

                mail.send(msg)

               

@app.route("/mail")

def SendMail():

        msg = Message('test',sender='zyfforlinux@163.com',recipients=['445188383@qq.com'])

        msg.body = "text body"

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

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

        thr.start()

        return "OK"

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Python下使用MySQLdb模块 http://www.linuxidc.com/Linux/2012-06/63620.htm

Python 的详细介绍请点这里
Python 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2014-07/104740.htm

linux
相关资讯       Flask-mail 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款