用python写一段代码,flask 异步发送带附件的邮件
时间: 2023-04-08 16:01:47 浏览: 149
以下是用 Python 编写的 Flask 异步发送带附件的邮件的代码:
```python
from flask import Flask, render_template, request
from flask_mail import Mail, Message
from threading import Thread
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'
)
mail = Mail(app)
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send_email', methods=['POST'])
def send_email():
recipient = request.form['recipient']
subject = request.form['subject']
body = request.form['body']
attachment = request.files['attachment']
msg = Message(subject, sender='your_email@gmail.com', recipients=[recipient])
msg.body = body
msg.attach(attachment.filename, attachment.read(), attachment.content_type)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return 'Email sent!'
if __name__ == '__main__':
app.run()
```
请注意,这只是一个示例代码,您需要将其适当修改以适应您的需求。
阅读全文