用Flask发送电子邮件

时间:2019-03-12 09:38:05

标签: python python-3.x flask timeoutexception flask-mail

我正在关注Miguel Grinberg撰写的Flask Web Development一书,他的“电子邮件”一章遇到了问题。

这些是他的配置:

import os
# ...
app.config["MAIL_SERVER"] = "smtp.googlemail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")

设置环境变量后,进入外壳并尝试运行以下代码:

(venv) $ flask shell
>>> from flask_mail import Message
>>> from hello import mail
>>> msg = Message("test email", sender="you@example.com", recipients=["you@example.com])
>>> msg.body = "This is plain text body"
>>> msg.html = "This is <b>HTML</b> body"
>>> with app.app_context():
...    mail.send(msg)
...

我的gmail设置正确,我遵循tutorial并执行了上述所有步骤。
我的代码产生以下错误:

Traceback (most recent call last):
  File "<console>", line 2, in <module>
  File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 491, in send
    with self.connect() as connection:
  File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 144, in __enter__
    self.host = self.configure_host()
  File "c:\...\flasky\venv\lib\site-packages\flask_mail.py", line 158, in configure_host
    host = smtplib.SMTP(self.mail.server, self.mail.port)
  File "C:\...\Python\Python37\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\...\Python\Python37\lib\smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\...\Python\Python37\lib\smtplib.py", line 307, in _get_socket
    self.source_address)
  File "C:\...\Python\Python37\lib\socket.py", line 727, in create_connection
    raise err
  File "C:\...\Python\Python37\lib\socket.py", line 716, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond

我发现了另外一个关于同一件事的question,并且尝试了其中提出的几项建议:

我换了线

app.config["MAIL_SERVER"] = "smtp.googlemail.com"

app.config["MAIL_SERVER"] = "smtp.gmail.com"

并且我对“ MAIL_USERNAME”和“ MAIL_PASSWORD”变量进行了硬编码,但再次遇到相同的错误。

由于没有任何效果,并且之前的问题很老(4年),我认为可能值得再次提出。

如果有人知道我在做什么错,请告诉我。
谢谢

2 个答案:

答案 0 :(得分:1)

确保您已允许次安全的应用连接到您的Google帐户。
这是链接:https://myaccount.google.com/lesssecureapps

答案 1 :(得分:0)

以下是对我有用的示例:

import os
from flask import Flask, jsonify
from flask_mail import Mail, Message

app = Flask(__name__)

app.config["MAIL_SERVER"]='smtp.gmail.com'
app.config["MAIL_PORT"]=587
app.config["MAIL_USE_TLS"]=False
app.config["MAIL_USE_SSL"]=True
app.config["MAIL_USERNAME"]=os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"]=os.environ.get("MAIL_PASSWORD")

mail = Mail(app)    
msg = Message(
              <your subject>,
              sender=os.environ.get("MAIL_USERNAME"),
              recipients=<recipiente e-mail>,
              html=<your html template>   
             )

@app.route('/sendmail')
def publish():    
   mail.send(msg)
   return jsonify({'message': 'Your message has been sent successfully'}), 200

if __name__ == '__main__':
       app.run()