From 8dbd54ac168202db5cfed9400d416a66300470a9 Mon Sep 17 00:00:00 2001 From: Jonathan Barratt Date: Mon, 12 Dec 2016 22:13:57 +0700 Subject: [PATCH] stop corrupting binary attachments when delivering them by email We accomplish this by attching files to out-bound mail diffrently depending on the versino of Python in effect. In Py2 we can read the files ourseles and the standard library will still be able to use the text we pass as if it were bytes. Under Py3, however, email.message will complain if it doesn't get to decode the bytes itself, so instead of attaching the contents directly we just pass the path to the file as a string instead. Unfortunately, Django 1.8 does not work with this Python 3 approach, due to its not yet having reverted to the newly improved standard library's mail-message implementation, and thus requiring us to know more about the character-encoding/mimetype of the attachment than I've been able to gather cleanly by this point. --- helpdesk/lib.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/helpdesk/lib.py b/helpdesk/lib.py index 73d309c0..8619fa26 100644 --- a/helpdesk/lib.py +++ b/helpdesk/lib.py @@ -21,6 +21,7 @@ except ImportError: from django.conf import settings from django.db.models import Q +from django.utils import six from django.utils.encoding import smart_text from django.utils.safestring import mark_safe @@ -121,7 +122,11 @@ def send_templated_mail(template_name, if files: for filename, filefield in files: - msg.attach(filename, open(filefield.path).read()) + if six.PY3: + msg.attach_file(filefield.path) + else: + with open(filefield.path) as attachedfile: + msg.attach(filename, attachedfile.read()) return msg.send(fail_silently)