第六章--电子邮件

一、使用Flask-Mail

pip install flask-mail

Flask-Mail连接到简单邮件传输协议(Simple Mail Transfer Protocol , SMTP)服务器,并将邮件交给这个服务器发送,如果不进行相关配置,Flask-Mail会连接到localhost上的25端口,无需验证即可发送邮件。

from flask.ext.mail import Mail
mail = Mail(app)    #初始化方法

二、在python shell中发送

python hello.py shell
from flask.ext.mail import Message
from htllo import mail
msg = Message('111111111', sender='[email protected]', recipients=['[email protected]'])
msg.body = 'text body'
msg.html = 'HTML body'
with app.app_context():
    mail.send(msg)

三、在程序中集成发送电子邮件

from flask.ext.mail import Message

app.config['FLASK_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASK_MAIL_SENDER'] = 'Flask Admin '

def send_eamil(to, subject, template, **kwargs):
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject)
            sender = app.config['FLASK_MAIL_SENDER'], recipients = [to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    mail.send(msg)

你可能感兴趣的:(第六章--电子邮件)