Flask-Mail是一个对python smtplib进行封装以便集成到Flask提供发送邮件支持的模块。在学习flask-mail遇到了两个问题,记录下来以便以后查看。
flask-mail安装
pip installl flask-mail
flask-mail的使用
代码如下:
#!/usr/bin/env python
import flask import Flask
from flask_mail import Message, Mail #现在flask-mail改为flask_mail导入
app = Flask(__name__)
#app.config['MAIL_SERVER'] = '220.181.12.16'
app.config['MAIL_SERVER'] = 'smtp.163.com' # 这里用163邮件服务器
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True # 启用安全传输层协议
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') # 从系统环境变量加载用户名和密码
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
mail = Mail(app)
# 创建邮件内容
msg = Message('email subject',sender='sender-email-address@163.com',
recipients=['reciver-email-address@exmple.com'])
msg.body='邮件正文内容'
# 发送邮件,没有包含附件
with app.app_context():
mail.send(msg)
# 发送邮件,包含有附件
with app.app_context():
with app.open_resource('test.png') as f:
# msg.attach 邮件附件添加
# msg.attach("文件名", "类型", 读取文件)
msg.attach('test.png','image/png',f.read())
mail.send(msg)
if __name__ == '__main__':
app.run()
执行这段代码遇到两个问题:
SMTP 530 认证失败,原因是开启了smtp服务,但是第三方邮件客户端要使用授权码登录,所以要在163邮箱上设置,设置客户端授权码,并使用户端授权码作为第三方邮件客户端的登录密码,即是代码中MAIL_PASSWORD的值。
SMTP error 554,在stackoverflow找到原因是DNS反向解析的问题,解决方法是把['MAIL_SERVER'] = 'smtp.163.com替换成['MAIL_SERVER'] = '220.181.12.16'
SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.
We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.