flask - 使用flask+blueprint发送邮件

标签 flask flask-mail

我对蓝图的结构有疑问

我的 flask 结构看起来像

app/
    main/
        __init__.py
        mail.py
    __init.py
manage.py
config.py

我在 __init__.py 中注册了 app/__init__.py

的蓝图
from flask_mail import Mail
from flask import Flask

mail = Mail()
def create_app(config_name='develop'):
    app = Flask(__name__)

    from config import cfg      # load EMAIL config from config.py
    app.config.from_object(cfg[config_name])
    cfg[config_name].init_app(app)

    from .main import main      # register blueprint
    app.register_blueprint(main)

    mail.init_app(app)          # load related mail config???

    return app

将配置放入config.py

class Config():
    MAIL_SERVER='<My e-mail SMTP>'
    MAIL_DEFAULT_SENDER=('TOPIC', 'mailID')
    MAIL_USERNAME='<EMail>'
    MAIL_PASSWORD='<EMail Password>'

当我在 app/main/mail.py 中编写这样的代码时,它会返回 smtplib.SMTPSenderRefused 错误

@main.route('/mail')
def sendmail():
    receivers = ['<Receiver 1>', '<Receiver 2>'] 
    app = current_app._get_current_object() # <class 'flask.app.Flask>
    mail = Mail(app)
    with mail.connect() as conn:
        for receiver in receivers:
            msg = Message(
                        subject='subject test',
                        recipients=[receiver],
                        html='<h1>Hi~~</h1>')
            mail.send(msg)
    return 'ok'

它引发 553 错误

smtplib.SMTPSenderRefused: (553, b'Domain name required.', '=?utf-8?q?<TOPIC>?= <mailID>')

我确实在app/__init__.py中加载了配置,但为什么我在app/main/mail.py中找不到MAIL_SERVER和相关配置?

但是如果我在 app/main/mail.py 中再次重新加载配置,它会成功发送邮件

app.config.update(
    MAIL_SERVER='<SMTP>',
    MAIL_DEFAULT_SENDER=('<TOPIC>', 'mailID'),
    MAIL_USERNAME='<email>',
    MAIL_PASSWORD='<PASSWORD>'
)

我不知道为什么我必须做两次

最佳答案

你应该像这样使用app_context():

from flask import current_app
from flask_mail import Message, Mail

with current_app.app_context():
    mail = Mail()
    mail.send(msg)

更多信息https://flask.palletsprojects.com/en/1.1.x/extensiondev/

关于flask - 使用flask+blueprint发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000681/

相关文章:

python - WTForms 在 Heroku 上引发 "TypeError: ' unicode' 没有缓冲区接口(interface)

python-2.7 - 如何使用 HTTPS 在 CherryPy WSGI 服务器 (Cheroot) 上运行 Flask 应用程序?

python - flask 邮件(python): Running out of application context error

python - Flask 邮件仅发送到某些域

python - 如何渲染和返回图以在 flask 中查看?

python - Flask 缓存 memoize 不适用于 Flask Restful 资源

python - 从测试文件夹导入 flask 模块失败

flask - 使用 Flask-Mail 发送邮件时连接被拒绝

python - 在 Flask 上注册用户时发送邮件时出现循环导入问题

python - Flask-Mail 尝试连接 Gmail 时超时