flask-mail__电子邮件

10 篇文章 0 订阅
特定事件发生时提请用户,常用的通信方式是电子邮件

smtplib包可在flask程序中发送电子邮件
flask-mail扩展,包装了smtplib包,更好的和flask进行集合

flask-mail提供电子邮件的支持

flask-mail连接到服务器(简单邮件传输协议),并将邮件交个这个服务器发送

进行配置

若不进行配置,flask-mail会连接localhost上的端口25,不需要验证,就可以发送电子邮件

设置smtp服务器的配置

连接都外部SMTP服务器

我使用的是网易邮箱

电子邮件的使用

1. 安装flask-mail

pip install flask-mail

2. 配置flask-mail使用网易
import os
...
app.config['MAIL_SERVER']='smtp.163.com'
app.config['MAIL_PORT']=25
app.config['MAIL_USE_TLS']=True
app.config['MAIL_USERNAME']='18856858578@163.com'
app.config['MAIL_PASSWORD']=`密码`

对于用户名和密码,在环境中定义

set MAIL_USERNAME = 18856858578@163.com
...
3. 初始化flask-mail
from flask.ext.mail import Mail
mail = Mail(app)
4. shell 中发送邮件
>>> from flask.ext.mail import Mail
>>> from hello import mail
>>> msg = Message('test subject',sender = 'you@example.com',recipients = ['you@example.com'])
>>> msg.body = 'test body
>>> msg.html = '<b>HTML</b> body
>>> with app.app_context():  #功能:激活程序上下文,获取程序的上下文
...     mail.send(msg) # 在激活的程序上下文环境中执行

程序上下文使用的方法
app.app_context()–>取当前应用程序的上下文,其中保存了,请求的信息,服务器信息,此时msg在其中等等

mail()函数使用current_app,因此要激活程序上下文中执行

5 . 程序中集成电子邮件功能

避免每次手写,jinja2模板渲染邮件文本

first

先写处电子邮件支持,发送邮件的函数

from flask.ext.mail import Message

app.config['WANG_MAIL_SUBJECT_PREFIX'] = '[WANG]'
app.config['WANG_MAIL_SENDER'] = 'you@example.com'

def send_email(to,suject,template,**kwargs):
    msg = Message('app.config[WANG_MAIL_SUBJECT_PREFIX]' + subject,
                  sender = app.config['WANG_MAIL_SENDER'],recipients = [to]  )
    msg.body = render_template(template+'.txt',**kwargs )
    msg.html = render_tmeplate(template+'.html',**kwargs)
    mail.send(msg)

1) app.config['WANG_MAIL_SUBJECT_PREFIX'] = '[WANG]'邮件主题前缀

app.config['WANG_MAIL_SENDER'] 发信人地址

2) send_email()参数:1.收件人地址to,主题suject,模板template,渲染邮件正文的模板的参数列表**kwargs

3) 指定模板时需要分别渲染纯文本和富文本,并将关键字参数传递到render_template()中
指定模板时不适用扩展名

msg.body = render_template(template+'.txt',**kwargs )
msg.html = render_tmeplate(template+'.html',**kwargs)

second:

hello.py中集成

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

@app.route('/',method = ['GOP','POST'])
def index():
    from = NameForm()
    if form.validate_on_sublim():
        user = User.query.filter_by(username = form.name.data).first()
        if user is None:
            db.session.add['user']
            session['known'] = False
            if app.config['WANG_ADMIN']:
                send_email(app.config['WANG_ADMIN'],'New User','mail/new_user',user = user)
        else:
            session['known'] = True
        session['name'] = 'form.name.data'
        form.name.data = ''
        return redirect(url_for('index'))
    return render_tmeplate('index.html',form =form,name = session.get('name'),known = session.get('known',False)

环境变量的使用
收件人保存在环境变量WANG_ADMIN中,程序启动过程中,环境变量加载到一个同名配置变量中

6. 创建两个模板,保存在mail/ner_user

用于渲染纯文本
用于渲染html的邮件正文

7. 异步发送邮件
from threading import Thread
#定义异步发送
def send_async_email(app,msg):
    with app.app_context():
        mail.send(msg)

def send_email(to,subject,template,**kwargs):
    msg = Message(app.config[WANG_MAIL_SUBJECT_PREFIX]+subject,sender = app.config['WANG_MAIL_SENDER'],recipients =[to])
    msg.doby = render_tmeplate(template,'.txt',**kwargs)
    msg.html = render_tmeplate(template,'.html',**kwargs)

    thr = threading.Thread(target = send_async_email,args = [app,msg])
    thr.start()
    return thr
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Flask-Mail是一个Flask扩展,它提供了发送电子邮件的功能。Mail类是Flask-Mail扩展中的一个主要类,它用于处理电子邮件的发送和配置。 Mail()函数是Mail类的构造函数,用于创建Mail对象实例。该函数的作用是初始化Mail对象,其中可以设置邮件服务器的配置信息,比如邮件服务器地址、端口号、邮件发送者等等。该函数可以接受多个参数,如下所示: ``` Mail(app=None, server=None, username=None, password=None, port=None, use_tls=None, use_ssl=None, default_sender=None, debug=False, max_emails=None, suppress=None, ascii_attachments=False) ``` 其中,各参数的含义如下: - app:Flask应用实例对象 - server:邮件服务器地址,可以是IP地址或域名 - username:邮件服务器的用户名 - password:邮件服务器的密码 - port:邮件服务器的端口号,默认为465 - use_tls:是否使用TLS加密传输,默认为False - use_ssl:是否使用SSL加密传输,默认为False - default_sender:默认的邮件发送者 - debug:是否开启调试模式,默认为False - max_emails:每个请求中发送的最大邮件数量,默认为None - suppress:是否禁止发送电子邮件,默认为False - ascii_attachments:是否将附件转换为ASCII格式,默认为False 通过Mail()函数创建Mail对象实例后,我们可以使用该对象的send()方法来发送电子邮件,如下所示: ``` mail = Mail() with app.app_context(): message = Message(subject='Hello', recipients=['xxx@example.com']) message.body = 'testing' mail.send(message) ``` 在上面的代码中,我们首先创建了一个Mail对象实例,然后使用with app.app_context()语句创建了一个应用上下文,接着创建了一个Message对象实例,设置了邮件主题和收件人地址,最后调用了Mail对象实例的send()方法来发送邮件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值