我正在尝试使用Flask-Mail发送电子邮件。我使用收件人创建邮件,但在尝试发送邮件时收到AssertionError: No recipients have been added
。在以下代码中,我打印出邮件收件人,它们是正确的。如何解决此错误?
from flask import Flask
from flask_mail import Message, Mail
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USERNAME='socialcreditsystem@gmail.com',
MAIL_PASSWORD='mypassword'
)
mail = Mail(app)
@app.route('/')
def hello_world():
msg=Message('hey hey hey', sender='socialcreditsystem@gmail.com', recipients=['julian.fink1000@gmail.com'])
print(msg.sender, msg.recipients)
# ('socialcreditsystem@googlemail.com', ['julian.fink1000@googlemail.com'])
print(msg.send_to)
# set(['julian.fink1000@googlemail.com'])
mail.send_message(msg)
return 'Hello World!'
if __name__ == '__main__':
app.run()
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Julian\PycharmProjects\flask_mail_test\flask_mail_test.py", line 26, in hello_world
mail.send_message(msg)
File "C:\Python27\lib\site-packages\flask_mail.py", line 503, in send_message
self.send(Message(*args, **kwargs))
File "C:\Python27\lib\site-packages\flask_mail.py", line 493, in send
message.send(connection)
File "C:\Python27\lib\site-packages\flask_mail.py", line 428, in send
connection.send(self)
File "C:\Python27\lib\site-packages\flask_mail.py", line 176, in send
assert message.send_to, "No recipients have been added"
AssertionError: No recipients have been added
答案 0 :(得分:3)
你使用了错误的功能。 mail.send_message
是构建和发送消息的快捷方式,它采用与Message
相同的参数。使用mail.send(msg)
发送现有的Message
实例。