Flask邮箱认证以及头像

Flask邮箱认证以及头像

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

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


发送邮件功能:

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'] = 'xxxxxx@qq.com'  # 填邮箱
    app.config['MAIL_PASSWORD'] = 'zzzzzzz'  # 填授权码
    app.config['MAIL_DEFAULT_SENDER'] = 'xxxxxxxxxxxx@qq.com'  # 填邮箱,默认发送者
    app.config['FLASKY_MAIL_SUBJECT_PREFIX']='[blog]'
    app.config['FLASKY_MAIL_SENDER']='xxxxxxxxxxx@qq.com'

头像功能通过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值