Flask邮箱认证以及头像

Flask邮箱认证以及头像

《Flask Web开发》书中关于邮箱认证功能此处使用qq邮箱完成。

首先到qq邮箱中开启SMTP服务,百度有很多教程。

Flask邮箱认证以及头像_第1张图片

发送邮件功能:

from threading import Thread
from flask import current_app, render_template
from flask.ext.mail import Message
from Main import mail


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

邮箱的配置:

app.config['MAIL_DEBUG'] = True  # 开启debug,便于调试看信息
    app.config['MAIL_SUPPRESS_SEND'] = False  # 发送邮件,为True则不发送
    app.config['MAIL_SERVER'] = 'smtp.qq.com'  # 邮箱服务器
    app.config['MAIL_PORT'] = 465  # 端口
    app.config['MAIL_USE_SSL'] = True  # 重要,qq邮箱需要使用SSL
    app.config['MAIL_USE_TLS'] = False  # 不需要使用TLS
    app.config['MAIL_USERNAME'] = '[email protected]'  # 填邮箱
    app.config['MAIL_PASSWORD'] = 'zzzzzzz'  # 填授权码
    app.config['MAIL_DEFAULT_SENDER'] = '[email protected]'  # 填邮箱,默认发送者
    app.config['FLASKY_MAIL_SUBJECT_PREFIX']='[blog]'
    app.config['FLASKY_MAIL_SENDER']='[email protected]'

头像功能通过avatar实现

def gravatar(self, size=100, default='identicon', rating='g'):
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)

根据用户邮箱生成对应的hash码发送到avatar网站即可生成头像

源码在:

https://github.com/LinZiYU1996/Flask-Email

你可能感兴趣的:(Flask)