[英]How to attach file to Flask Mail received from Flask Form?
I am developing a website in Python Flask. 我正在用Python Flask开发一个网站。 What I have to do is to get uploaded file in one of the forms and attach it to mail.
我要做的是以一种形式获取上传的文件,并将其附加到邮件中。 I tried solution given in similar question but it gives following error:
我尝试了类似问题中给出的解决方案,但出现以下错误:
AttributeError: 'str' object has no attribute 'filename'
AttributeError:'str'对象没有属性'filename'
What am I doing wrong? 我究竟做错了什么? I am beginner in python and flask.
我是python和flask的初学者。 Here's my code:
这是我的代码:
class UploadForm(Form):
branch = StringField('branch', validators = [DataRequired()])
year = StringField('year', validators = [DataRequired()])
sub = StringField('sub', validators = [DataRequired()])
paper = FileField('Logo', validators = [Required()])
def uploadPaper(form):
msg = Message('New upload request', sender = ADMINS[0], recipients = ADMINS)
msg.body = 'text body'
msg.html = 'Branch: ' + form.branch.data + '<br />' + 'Year: ' + form.year.data + '<br />' + 'Subject: ' + form.sub.data
msg.attach(form.paper.data.filename, 'application/octect-stream', form.paper.data.read())
with app.app_context():
mail.send(msg)
return "success"
I am calling uploadPaper() function on validating the form. 我在验证表单时调用uploadPaper()函数。
Well, the error you've got means you're trying to read a file from a string. 好吧,您收到的错误意味着您正在尝试从字符串中读取文件。
AttributeError: 'str' object has no attribute 'filename'
This happens because your uploadPaper() function is returning a string (Or 'str') instead of a 'file' object. 发生这种情况是因为您的uploadPaper()函数返回的是字符串(或“ str”),而不是“ file”对象。 Since Python is object-oriented, your script is probably trying to read the "filename" attribute from the file object.
由于Python是面向对象的,因此您的脚本可能正在尝试从文件对象读取“文件名”属性。
I can also see in your function that there is an object with the attribute you're trying to use, here at 我还可以在您的函数中看到,有一个具有您要使用的属性的对象,在这里
msg.attach(form.paper.data.filename, 'application/octect-stream', form.paper.data.read())
It looks like the form.paper.data
object has the property "filename" you're trying to user later on. 看起来
form.paper.data
对象具有您稍后要尝试使用的属性“文件名”。
Why don't you try return form.paper.data
instead of return "success"
? 为什么不尝试
return form.paper.data
而不是return "success"
呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.