请给我一个flask 发送邮件的案例
时间: 2023-12-03 22:42:51 浏览: 27
好的,以下是一个使用 Flask 发送邮件的示例代码:
```python
from flask import Flask, render_template, request, flash
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME='your_email@gmail.com',
MAIL_PASSWORD='your_password'
)
app.secret_key = 'secret_key'
mail = Mail(app)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
message = request.form['message']
# Send email
msg = Message(subject='Message from your website',
sender=app.config.get('MAIL_USERNAME'),
recipients=[email])
msg.body = f'Hello {name},\n\nThank you for contacting us. Your message has been received and we will get back to you as soon as possible.\n\nBest regards,\nYour website team\n\nYour message: {message}'
mail.send(msg)
flash('Your message has been sent successfully!')
return render_template('home.html')
return render_template('home.html')
if __name__ == '__main__':
app.run()
```
在上面的代码中,我们首先配置了 Flask-Mail 所需的参数,包括 SMTP 服务器地址、端口号、是否启用 TLS 加密、发件人邮箱和密码。然后,我们创建了一个名为 `mail` 的 `Mail` 对象,并将其与 Flask 应用程序 `app` 关联。
接下来,我们定义了一个名为 `home` 的路由函数,用于处理用户提交的表单数据。当用户提交表单时,我们首先从 `request.form` 中获取用户输入的姓名、邮箱和消息。然后,我们创建一个 `Message` 对象,设置邮件主题、发件人和收件人,并将消息内容添加到邮件正文中。最后,我们使用 `mail.send()` 方法发送邮件,并使用 Flask 的 `flash()` 函数提示用户消息已成功发送。
最后,我们在 `if __name__ == '__main__':` 代码块中启动应用程序。