该程序将上传文件并将其附加到电子邮件中。电子邮件服务器设置存储在settings.py
.
#!/usr/bin/env python
from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from flask_wtf.file import FileField
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.from_object('settings')
mail = Mail(app)
class FileForm(FlaskForm):
file_ = FileField('Some file')
addr = StringField('Address', [validators.InputRequired()])
@app.route('/', methods=['GET', 'POST'])
def root():
form = FileForm()
if form.validate_on_submit():
msg = Message(
'Sending file',
sender=form.addr.data.strip(),
recipients=[form.addr.data.strip()])
msg.body = 'Sending file %s' % (form.file_.name)
msg.attach(
form.file_.data.filename,
'application/octect-stream',
form.file_.data.read())
mail.send(msg)
return "Sent"
return render_template_string('''
<html><body><form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.addr.label }}: {{ form.addr() }}<br/>
{{ form.file_.label }}: {{ form.file_() }}<br/>
<input type="submit" value="Click Me!"/>
</form></body></html>''', form=FileForm())
if __name__ == '__main__':
app.run(debug=True)