烧瓶WTF到烧瓶邮件附件?

时间:2016-10-29 05:41:03

标签: python wtforms flask-wtforms flask-mail

通过flask-wtf上传文件,然后使用flask-mail

邮寄
def careers():
    form = CareersForm()

    if form.validate_on_submit():
        msg = Message('my subject for message', sender = MAIL_USERNAME, recipients = [company_email])
        msg.html = "My message"
        with app.open_resource(form.resume) as fp:
            msg.attach("resume.pdf", "application/pdf", fp.read())
        mail.send(msg)

    return render_template('default/careers.html',form=form)

我得到的错误是AttributeError: 'FileField' object has no attribute 'startswith'理想的结果是附加和发送电子邮件。

1 个答案:

答案 0 :(得分:3)

此程序将上传文件并将其附加到电子邮件中。电子邮件服务器设置存储在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)