电子邮件(二)


书外资料

flask-mail中文文档

配置 Flask-Mail
发送邮件
大量邮件
附件
单元测试以及禁止发送邮件

发送邮件
为了能够发送邮件,首先需要创建一个 Message 实例:

from flask_mail import Message

@app.route("/")
def index():

    msg = Message("Hello",
                  sender="[email protected]",
                  recipients=["[email protected]"])

你能够设置一个或者多个收件人:

msg.recipients = ["you@example.com"]
msg.add_recipient("somebodyelse@example.com")

如果你设置了 MAIL_DEFAULT_SENDER,就不必再次填写发件人,默认情况下将会使用配置项的发件人:

msg = Message("Hello",
              recipients=["[email protected]"])

如果 sender 是一个二元组,它将会被分成姓名和邮件地址:

msg = Message("Hello",
              sender=("Me", "me@example.com"))
assert msg.sender == "Me @example.com>"

邮件内容可以包含主体以及/或者 HTML:

msg.body = "testing"
msg.html = "testing"

最后,发送邮件的时候请使用 Flask 应用设置的 Mail 实例:

mail.send(msg)

正文

from flask_mail import Mail, Message
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
###主题前缀从环境变量获取
app.config['FLASKY_MAIL_SENDER'] = '[email protected]'
###书上是代码:
###app.config['FLASKY_MAIL_SENDER']='FlaskyAdmin'
###他的意思填入管理员的邮箱,Flasky Admin和<>都得去掉
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
###FLASKY_ADMIN从环境变量获取
...
def send_email(to, subject, template, **kwargs):
###定义send_email()函数的参数分别是收件箱地址,主题,渲染邮件正文的模板和关键字参数
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + '' + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
###为了能够发送邮件,首先需要创建一个 Message 实例,里面配置了主题前缀,发送人邮件地址,接收人
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
###邮件内容可以包含主体以及/或者 HTML,send_email()里的关键字参数**kwargs传给render_template()函数,以便在模板中使用
###指定模板是不能包含扩展名,这样才能使用两个模板分别渲染纯文本正文和富文本正文。
    mail.send(msg)
###最后,发送邮件的时候请使用 Flask 应用设置的 Mail 实例
...
@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            session['known'] = False
            if app.config['FLASKY_ADMIN']:
            ###如果已经在环境设置了'FLASKY_ADMIN',
            ###提取他的值,为None不执行,有值执行
                send_email(app.config['FLASKY_ADMIN'], 'New User',
                          'mail/new_user', user=user)
###执行send_mail()函数,
###参数to传入的是接收者管理员邮件地址,
###subject传入的是自己提前设置的主题前缀,template传入的是提前设置的模板文件,
###**kwargs关键字参数是user=user,代表的是把表中新填入的名字传入user变量供send_email()函数中的render_template的关键字参数使用,进而替换模板中的user变量。
        else:
            session['known'] = True
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', 
        form=form,name=session.get('name'),
        known=session.get('known', False))

templates/mail文件夹下的两个文件夹new_user.html和new_user.txt:
电子邮件模板中要有一个模板参数是用户,因此调用send_email()函数时要以关键字参数的形式传入用户。

###templates/mail/new_user.html
User <b>{{ user.username }}b> has joined.
###templates/mail/new_user.txt
User {{ user.username }} has joined.

运行命令:
(venv) C:\Users\Geek Lee\Geek-Lee.github.io>set [email protected]
(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py runserver

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>set
FLASKY_ADMIN=2546701377@qq.com
(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py runserver
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
...
  File "hello.py", line 93, in index
    if app.config['FLASKY_ADMIN']:
KeyError: 'FLASKY_ADMIN'
127.0.0.1 - - [21/Sep/2016 11:39:08] "POST / HTTP/1.1" 500 

###缺少从环境接受FLASKY_ADMIN配置的代码
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')

...
  File "C:\Users\GEEKLE~1\GEEK-L~1.IO\venv\lib\site-packages\flask\templating.py
", line 85, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: mail/new_user.txt
127.0.0.1 - - [21/Sep/2016 11:43:22] "POST / HTTP/1.1" 500 

###这一次是缺少了mail/new_user.txt

smtplib.SMTPSenderRefused: (501, b'mail from address must be same as authorizati
on user', 'Flasky Admin [email protected]')
127.0.0.1 - - [21/Sep/2016 11:44:09] "POST / HTTP/1.1" 500 -

###这一次是把书上抄一遍
###app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin
'
###其实应该是app.config['FLASKY_MAIL_SENDER'] = '2546701377@qq.com'

(venv) C:\Users\Geek Lee\Geek-Lee.github.io>python hello.py runserver
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [21/Sep/2016 11:48:56] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Sep/2016 11:49:01] "POST / HTTP/1.1" 302 -
127.0.0.1 - - [21/Sep/2016 11:49:01] "GET / HTTP/1.1" 200 -
电子邮件(二)_第1张图片

你可能感兴趣的:(-----flask)