烧瓶WTF到烧瓶邮件附件?
Posted
技术标签:
【中文标题】烧瓶WTF到烧瓶邮件附件?【英文标题】:Flask WTF to flask-mail attachment? 【发布时间】:2016-10-29 05:41:02 【问题描述】:通过 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】:此程序将上传文件并将其附加到电子邮件中。电子邮件服务器设置存储在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)
【讨论】:
以上是关于烧瓶WTF到烧瓶邮件附件?的主要内容,如果未能解决你的问题,请参考以下文章