Upload a file via flask-wtf and then mail it using 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)
The error i get is AttributeError: 'FileField' object has no attribute 'startswith'
ideal result would be for it to attach and send email.
This program will upload a file and attach it to an email message. The email server settings are stored in 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.