我有一个关于蓝图结构的问题
我的烧瓶结构看起来像
app/
main/
__init__.py
mail.py
__init.py
manage.py
config.py我为app/__init__.py在__init__.py中注册blueprint
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>'
)我不知道为什么我要做两次
发布于 2020-03-02 18:33:39
您应该像这样使用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/
发布于 2020-03-02 21:22:16
下面的代码是渲染HTML模板,用于发送邮件正文,包括样式或格式化的HTML。
from <project-module> import mail
token = user.get_reset_token()
msg = Message('Password Reset Request', sender='<sender-mail>', recipients=[user.email])
msg.html = render_template('email_templates/password_reset.html',
home_link=url_for('home.index', _external=True),
reset_link=url_for(
'account.reset_token', token=token, _external=True),
name=user.name,
email=user.email)
mail.send(msg)正如你上面提到的代码。我已经初始化了两次邮件对象,这是不必要的。
@main.route('/mail')
def sendmail():
receivers = ['<Receiver 1>', '<Receiver 2>']
mail = Mail()
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'发布于 2018-06-09 02:33:19
不是直接回答你的问题,但实际上我认为你不需要初始化邮件两次。
如果您想在app/main/mail.py中初始化邮件,那么在app/__init__.py中使用mail.init_app(app)是没有意义的,因为您从未导入过它。
否则,在app/main/mail.py中,我会在不创建另一个邮件的情况下执行import app.mail,这样您就不会在一开始就有这个配置问题。
https://stackoverflow.com/questions/49000681
复制相似问题