使用Flask wtf表单通过电子邮件发送附件可以通过以下步骤实现:
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField, FileRequired
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['MAIL_SERVER'] = 'your_mail_server'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your_username'
app.config['MAIL_PASSWORD'] = 'your_password'
mail = Mail(app)
class MyForm(FlaskForm):
file = FileField('Attachment', validators=[FileRequired()])
submit = SubmitField('Send')
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
file = form.file.data
filename = secure_filename(file.filename)
file.save(os.path.join(app.root_path, 'uploads', filename))
msg = Message('Attachment', sender='your_email', recipients=['recipient_email'])
msg.attach(filename, 'application/octet-stream', file.read())
mail.send(msg)
return 'Email sent successfully!'
return render_template('index.html', form=form)
<!DOCTYPE html>
<html>
<head>
<title>Flask WTF Form</title>
</head>
<body>
<h1>Send Attachment</h1>
<form method="POST" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.file.label }} {{ form.file }}
{{ form.submit }}
</form>
</body>
</html>
以上代码实现了一个简单的Flask应用,通过wtf表单上传文件并通过电子邮件发送附件。在使用时,需要替换相应的配置参数和邮件信息。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云