flask email 完整详细案例
时间: 2023-08-14 11:07:23 浏览: 54
以下是一个基于 Flask 的完整邮件发送案例:
```python
from flask import Flask, render_template, request, redirect, url_for
from flask_mail import Mail, Message
app = Flask(__name__)
# 配置邮件相关参数
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your_email@qq.com' # 发件人邮箱
app.config['MAIL_PASSWORD'] = 'your_email_password' # 发件人邮箱密码
# 初始化 Flask-Mail
mail = Mail(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send_email', methods=['GET', 'POST'])
def send_email():
if request.method == 'POST':
# 获取表单提交数据
recipient = request.form['recipient']
subject = request.form['subject']
content = request.form['content']
# 创建邮件消息对象
msg = Message(subject=subject,
sender=app.config['MAIL_USERNAME'],
recipients=[recipient])
msg.body = content
# 发送邮件
mail.send(msg)
# 跳转到发送成功页面
return redirect(url_for('success'))
return render_template('send_email.html')
@app.route('/success')
def success():
return render_template('success.html')
if __name__ == '__main__':
app.run(debug=True)
```
在上面的代码中,我们首先通过 Flask-Mail 库来配置邮件参数,然后初始化 Flask-Mail。在 `/send_email` 路由中,我们获取表单提交的数据,在创建一个邮件消息对象,然后通过 `mail.send()` 方法来发送邮件。如果发送成功,我们将跳转到 `/success` 路由,展示发送成功的页面。
需要注意的是,在使用 Flask-Mail 发送邮件时,我们需要确保发件人邮箱的 SMTP 服务已经开启。另外,在使用 QQ 邮箱发送邮件时,需要使用腾讯的 SSL 端口(465),否则会收到“SMTPAuthenticationError: (535, b'Error: authentication failed')”的错误提示。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)