我正在尝试通过 Flask 邮件使用 gevent 在 Flask 中异步发送电子邮件。我正在“在应用程序上下文之外工作”。我知道 app.app_context() 但我无法让它与我的设置一起工作。
我的应用程序是用这样的应用程序工厂创建的:
我的项目/run_dev.py
from gevent.wsgi import WSGIServer
from my_project.app import create_app
from my_project.config import DevConfig
app = create_app(DevConfig)
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
我的项目/我的项目/app.py
def create_app(config=None, app_name=None, blueprints=None):
app = Flask(app_name)
configure_app(app, config)
<other stuff>
return app
Run Code Online (Sandbox Code Playgroud)
以及我用来发送电子邮件的代码:
我的项目/我的项目/我的模块/views.py
@mymodule.route('/some/path/')
def do_something():
do_stuff(something)
Run Code Online (Sandbox Code Playgroud)
我的项目/我的项目/我的模块/utils.py
def do_stuff(something):
send_email(msg)
@async
def send_async_email(msg):
mail.send(msg)
def send_mail(request_id, recipients, email_type, env=None, pool=None):
msg = Message(
sender=sender,
recipients=recipients,
subject=subject,
body=body)
send_async_email(msg)
Run Code Online (Sandbox Code Playgroud)
我的项目/我的项目/decorators.py
def async(f):
def wrapper(*args, **kwargs): …Run Code Online (Sandbox Code Playgroud) 我们有一个Web应用程序,它向客户端发送电子邮件,并且该Web应用程序正在使用Flask邮件框架进行处理。大约2周前,我们的Web应用程序未能将电子邮件发送给客户和我们自己的团队。我们使用Office 365的Outlook作为发件人。
远程服务器返回'554 5.6.0损坏的消息内容;STOREDRV.Deliver.Exception:ConversionFailedException; 由于消息内容转换的永久异常而无法处理消息:TNEF摘要内容已损坏。ConversionFailedException:内容转换:概要TNEF内容已损坏。[阶段:PromoteCreateReplay]'原始邮件标题:
这是发件人被指示发送电子邮件后收到的错误消息。我们联系了Office 365管理员,Microsoft告诉他我们的Web应用程序具有的安全性不符合Microsoft的要求/协议。
问题是Flask邮件使用的旧版安全协议或配置无法与Microsoft Outlook很好地配合吗?
这是我用来发送邮件以重置密码的主要烧瓶邮件代码,以防用户忘记,但当我运行和编码时,它看到我 smtplib.SMTPServerDisconnected:连接意外关闭
下面是init.py文件代码
import os
from flask_mail import Mail
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = '7f09c01a4f942b0812be4cb86e065f77'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'
db=SQLAlchemy(app)
bcrypt=Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view='login'
login_manager.login_message_category='info'
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'sender@gmail.com'
app.config['MAIL_PASSWORD'] = 'password'
mail = Mail(app)
from index import routes
Run Code Online (Sandbox Code Playgroud)
和routes.py文件
import os
import binascii
from PIL import Image
from flask import render_template,url_for, flash, …Run Code Online (Sandbox Code Playgroud) 我正在使用 Flask 和应用程序工厂设计模式构建一个应用程序。我想在我的一个视图中使用 Flask-Mail,该视图通过蓝图注册到应用程序。
我从这个Flask - Cannot use Flask and Flask-mailInstances from other files问题中看到,您应该在 create_app() 函数之外实例化 Mail() 对象,如下所示:
from flask_mail import Mail
mail = Mail()
def create_app(config_lvl):
# stuff
mail.init_app(app)
# more stuff
return app
Run Code Online (Sandbox Code Playgroud)
然后,您可以将邮件对象导入到视图文件中并从那里访问它。
但是,要使其正常工作,您需要确保在导入包含使用邮件对象的视图的蓝图之前__init__.py实例化应用程序中的邮件对象。如果不这样做,您会收到导入错误。
对我来说,这感觉很奇怪,尽管 Flask 通常似乎对这类事情很满意,但我希望应用程序工厂设计模式能够最大限度地减少这种导入的麻烦。
我的解决方案是将邮件客户端附加到应用程序对象,以便可以从其他任何地方访问它,current_app.mail如下所示:
## __init.py __ ##
from flask_mail import Mail
def create_app(config_lvl):
# stuff
app.mail = Mail(app)
# more stuff
return app
## views.py ##
from flask_mail import Message
from flask import current_app
def …Run Code Online (Sandbox Code Playgroud) 我的烧瓶项目基于Flask-Cookiecutter,我需要异步发送电子邮件。
发送电子邮件的功能由Miguel的教程配置,并且可以同步发送,但我不知道如何修改它以异步发送。
我的app.py
def create_app(config_object=ProdConfig):
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
return app
def register_extensions(app):
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
migrate.init_app(app, db)
mail.init_app(app)
return None
Run Code Online (Sandbox Code Playgroud)
我的view.py
from flask import current_app
@async
def send_async_email(current_app, msg):
with current_app.app_context():
print('##### spustam async')
mail.send(msg)
# Function for sending emails
def send_email(to, subject, template, **kwargs):
msg = Message(subject, recipients=[to])
msg.html = render_template('emails/' + template, **kwargs)
send_async_email(current_app, msg)
Run Code Online (Sandbox Code Playgroud)
在view.py中路由
@blueprint.route('/mailer', methods=['GET', 'POST'])
def mailer():
user = current_user.full_name
send_email(('name@gmail.com'),
'New mail', …Run Code Online (Sandbox Code Playgroud) 我正在 Flask 上编写一个网站,遇到了向电子邮件用户发送电子邮件时出现这样的错误的问题。
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials i1-20020ac25221000000b00478f5d3de95sm4732790lfl.120 - gsmtp')
Run Code Online (Sandbox Code Playgroud)
我在Google上搜索了该问题的解决方案,但它说你需要禁用最近GMAIL不支持的功能。也许现在有人知道如何解决这个问题?
这是我的配置连接:
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')
Run Code Online (Sandbox Code Playgroud)
请帮帮我
我正在按照烧瓶教程练习做烧瓶邮件,但我遇到了一些似乎是个bug的东西.我不明白发生了什么?
这是我的代码:
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
mail.send(msg)
Run Code Online (Sandbox Code Playgroud)
这是bug的信息:
Traceback (most recent call last):
File "ch6_1.py", line 64, in <module>
send_email(app ,MAIL_USERNAME, "test mail", "hello")
File "ch6_1.py", line 50, in send_email
msg.body = render_template(template + '.txt', **kwargs)
File "D:\INSTALL\Python\lib\site-packages\flask\templating.py", line 126, in r
ender_template
ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'
Run Code Online (Sandbox Code Playgroud) 我正在试验 Flask-Security,但在发送确认电子邮件时遇到了一些问题。我最终通过删除 flask_security/utils.py 中的一行来修复它。我删除了第 387 行,强制烧瓶邮件使用 app.config 的邮件发件人。
386: msg = Message(subject,
387: sender=_security.email_sender,
388: recipients=[recipient])
Run Code Online (Sandbox Code Playgroud)
在删除之前,代码将在flask_mail.py,@第105 行(在sanatize_address 方法内)中失败,因为传入的addr 只是一个字符串,而不是元组。
102: def sanitize_address(addr, encoding='utf-8'):
103: if isinstance(addr, string_types):
104: addr = parseaddr(force_text(addr))
105: nm, addr = addr
Run Code Online (Sandbox Code Playgroud)
我希望能够运行我的代码而不必在每次安装时修改 flask_security/utils.py。有什么建议?我的配置中可能缺少一个步骤,但我无法从flask-security 的文档中分辨出来(它们有点有限)。
感谢您的帮助,下面是我的示例应用程序。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
import flask_security.utils
import flask_mail
# Create app
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
# Flask-Security Config …Run Code Online (Sandbox Code Playgroud) 当通过 Flask-Mail 发送任何消息时,如下所示,最后一行mail.send(msg)也将导致邮件标题和内容被记录。
Message("Hello", sender="from@example.com", recipients=["to@example.com"])
msg.body = 'anything'
mail.send(msg)
Run Code Online (Sandbox Code Playgroud)
由于我的邮件可能包含敏感信息,我想完全禁用此日志记录。然而,在使用日志模块时,我找不到为 Flask-Mail 配置的记录器。
如何禁用 Flask-Mail 中的日志记录?
from flask import current_app as app
from flask import render_template
from threading import Thread
from flask_mail import Message
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['MAIL_SENDER'], recipients=[to])
# msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=(app,msg))
thr.start()
return thr
#mail.send(msg)
Run Code Online (Sandbox Code Playgroud)
运行时错误:在应用程序上下文之外工作。
这通常意味着您尝试使用需要以某种方式与当前应用程序对象交互的功能。要解决此问题,请使用 app.app_context() 设置应用程序上下文。请参阅文档以获取更多信息。
我以为我已经创建了 app_context,但代码仍然显示运行时错误。请帮忙,谢谢。
flask-mail ×10
python ×10
flask ×9
python-3.x ×2
email ×1
gevent ×1
gmail ×1
office365 ×1
outlook ×1