我有以下代碼:
藍圖檔案片段:
...
from flask_mail import Message
from app import mail
from os import environ
...
@index_bp.route('/contact', methods=['POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
print('Form received')
msg = Message('Test', recipients=environ.get('TARGET_MAIL'))
print('msg created')
msg.body = 'Test mail'
print('Body created')
mail.send(msg)
print('Mail sent')
return redirect(url_for('.index'))
組態檔:
class Config:
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
SECRET_KEY = environ.get('SECRET_KEY')
MAIL_SERVER = 'smtp.google.com'
MAIL_PORT = 465
MAIL_USERNAME = environ.get('MAIL_USERNAME')
MAIL_PASSWORD = environ.get('MAIL_PASSWORD')
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_DEFAULT_SENDER = environ.get('MAIL_USERNAME')
初始化檔案:
from flask import Flask
from flask_mail import Mail
mail = Mail()
def init_app():
# Set up core app
app = Flask(__name__)
app.config.from_object('config.Config')
mail.init_app(app)
with app.app_context():
# Import app routes
from .index import routes
# Register blueprints
app.register_blueprint(routes.index_bp)
return app
當我嘗試測驗應用程式的電子郵件功能時,這mail.send(...)部分只是舉手。它永遠不會解決,實際上不會引發任何錯誤,而是永遠保持頁面加載。很可能與 Gmail 有關,但我不知道缺少什么。
非常感謝任何幫助。以下是代碼生成的列印件:
收到的表格
已創建味精
身體創建
繼續避免做任何其他事情離開頁面加載
** 更新 **
這是我為使用 Gmail 測驗 Flask Mail 而制作的另一個片段,但仍然出現相同的錯誤:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.google.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '<new gmail account>@gmail.com'
app.config['MAIL_PASSWORD'] = '<app password>'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello from the other side!', sender = '<new gmail account>@gmail.com', recipients = ['<my gmail address>@gmail.com'])
msg.body = "This is a test email"
mail.send(msg)
return "Message sent!"
編輯:
錯誤是使用 smtp.google.com 而不是 smtp.gmail.com,但是,此處發布的答案也有很大幫助:)。
uj5u.com熱心網友回復:
由于您的 Google 帳戶,Google 最近更改了一些安全功能,不讓不太安全的應用程式僅使用用戶名和密碼登錄您的帳戶,您可以在 MAIL_PASSWORD 配置中使用應用程式密碼而不是您的 Google 帳戶密碼來解決問題
在下面的鏈接中,我回答了同樣的問題,您可以檢查一下
Google 禁止訪問不太安全的應用
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485652.html
上一篇:在燒瓶規則中處理url
