flsak 使用email 完整案例
时间: 2023-07-11 20:06:53 浏览: 43
下面是使用 Flask 发送邮件的完整示例代码:
```python
from flask import Flask, render_template, request
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your_email@gmail.com'
app.config['MAIL_PASSWORD'] = 'your_email_password'
mail = Mail(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send_email', methods=['POST'])
def send_email():
name = request.form['name']
email = request.form['email']
message = request.form['message']
msg = Message(subject='New Message from your website', sender='your_email@gmail.com', recipients=['your_email@gmail.com'])
msg.body = f"Name: {name}\nEmail: {email}\nMessage: {message}"
mail.send(msg)
return render_template('success.html')
if __name__ == '__main__':
app.run(debug=True)
```
在这个例子中,我们使用 Flask-Mail 扩展来发送邮件。首先,我们需要设置邮件服务器的信息,例如 SMTP 服务器地址,端口号,以及使用 SSL 进行加密等。然后,我们创建 Mail 实例,并将其与 Flask 应用关联。
在 `/send_email` 路由中,我们从表单中获取用户提交的姓名、电子邮件和消息,然后使用 Message 类创建一个邮件对象。我们设置邮件主题、发件人和收件人,然后将邮件正文设置为包含用户输入的信息的字符串。最后,我们调用 `mail.send()` 方法来发送邮件。
在这个例子中,我们只是简单地渲染了一个成功页面来通知用户邮件已经成功发送。您可以根据自己的需求进行更改。