I'm using the following function in my program to send emails:
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(filename) as fp:
msg.attach(filename, fp.read())
mail.send(msg)
The email works fine and sends to the to the correct user, however the attatchment does not, I believe I may be referencing this incorrectly as the file attachment comes from the form.
I have used the function below to save the attachment and this works fine so I'm not sure why the above is not working, can anyone assist?
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)
return redirect('home')
Edit: When trying to submit error message received is:
[Errno 2] No such file or directory: 'C:\\Users\\richard.danvers\\application\\answer.docx'
Looks as if 'uploads' is not included in the path, anyone know how to include this?
A content type needs to be specified within the msg.attach argument.
e.g. 'text/plain'