推荐答案
// 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 the email body"
mail.send(msg)
return "Mail sent"
if __name__ == '__main__':
app.run(debug=True)本题详细解读
1. 安装 Flask-Mail
首先,你需要安装 Flask-Mail 扩展。可以通过 pip 安装:
pip install Flask-Mail
2. 配置 Flask-Mail
在 Flask 应用中,你需要配置 Flask-Mail 的相关参数,包括邮件服务器地址、端口、是否使用 TLS、用户名和密码等。这些配置通常放在 app.config 中。
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'
3. 初始化 Mail 对象
在配置完成后,你需要初始化 Mail 对象:
mail = Mail(app)
4. 创建邮件消息
使用 Message 类来创建邮件消息。你需要指定邮件的主题、发件人、收件人以及邮件内容。
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.body = "This is the email body"5. 发送邮件
最后,使用 mail.send() 方法发送邮件:
mail.send(msg)
6. 完整示例
将上述步骤整合到一个 Flask 路由中,即可实现通过访问 /send-mail 路由来发送邮件。
@app.route('/send-mail')
def send_mail():
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.body = "This is the email body"
mail.send(msg)
return "Mail sent"7. 运行应用
确保在 if __name__ == '__main__': 块中运行应用:
if __name__ == '__main__':
app.run(debug=True)通过以上步骤,你可以在 Flask 应用中使用 Flask-Mail 扩展发送邮件。