推荐答案
在 Flask 中发送邮件可以通过 Flask-Mail 扩展来实现。以下是一个简单的示例代码:
// www.javascriptcn.com code example
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
# 配置邮件服务器
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your-email@example.com'
app.config['MAIL_PASSWORD'] = 'your-email-password'
mail = Mail(app)
@app.route('/send-mail')
def send_mail():
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.body = "This is a test email sent from Flask."
mail.send(msg)
return "Mail sent!"
if __name__ == '__main__':
app.run(debug=True)本题详细解读
1. 安装 Flask-Mail
首先,你需要安装 Flask-Mail 扩展。可以通过以下命令安装:
pip install Flask-Mail
2. 配置邮件服务器
在 Flask 应用中,你需要配置邮件服务器的相关信息。常见的配置项包括:
MAIL_SERVER: 邮件服务器地址,例如smtp.example.com。MAIL_PORT: 邮件服务器端口,通常为587。MAIL_USE_TLS: 是否使用 TLS 加密,通常设置为True。MAIL_USERNAME: 发件人的邮箱地址。MAIL_PASSWORD: 发件人的邮箱密码。
3. 创建邮件对象
使用 Message 类创建邮件对象。你需要指定邮件的主题、发件人、收件人以及邮件内容。
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.body = "This is a test email sent from Flask."4. 发送邮件
通过 mail.send(msg) 方法发送邮件。
mail.send(msg)
5. 运行 Flask 应用
最后,运行 Flask 应用并访问 /send-mail 路由,邮件将会被发送。
python app.py
通过以上步骤,你可以在 Flask 应用中轻松地发送邮件。