我对蓝图的结构有疑问
我的 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/