我有一个功能,可以在用户提交我的表单并上传文件时保存附件,此功能还发送电子邮件。我希望此功能使用提交的文件作为电子邮件的附件。我试图这样做:
def send_email(subject, sender, recipients, text_body):
FILE_TYPES = set(['txt', 'doc', 'docx', 'odt', 'pdf', 'rtf', 'text', 'wks', 'wps', 'wpd'])
form = ApplicationForm (request.files)
submit_name = form.file_upload.data.filename
mail = Mail(app)
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
filename = secure_filename(submit_name)
form.file_upload.data.save('uploads/' + filename)
with app.open_resource('uploads/' + filename) as fp:
msg.attach(filename, fp.read()) #attaches the submitted file to the email
print 'file sent successfully'
mail.send(msg)
编辑:现在收到以下错误:
TypeError: __init__() takes exactly 3 arguments (75 given)
追溯:
Traceback (most recent call last):
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\PYTHON27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\richard.danvers\application\app\views.py", line 87, in index
department_data=form.department.data
File "C:\Users\richard.danvers\application\app\views.py", line 30, in send_email
mail.send(msg) # if no file is uploaded email is sent without any attachment
File "C:\PYTHON27\lib\site-packages\flask_mail.py", line 492, in send
message.send(connection)
File "C:\PYTHON27\lib\site-packages\flask_mail.py", line 427, in send
connection.send(self)
File "C:\PYTHON27\lib\site-packages\flask_mail.py", line 190, in send
message.as_bytes() if PY3 else message.as_string(),
File "C:\PYTHON27\lib\site-packages\flask_mail.py", line 381, in as_string
return self._message().as_string()
File "C:\PYTHON27\lib\site-packages\flask_mail.py", line 349, in _message
f = MIMEBase(*attachment.content_type.split('/'))
TypeError: __init__() takes exactly 3 arguments (75 given)