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.
This commit is contained in:
Jonathan Barratt 2016-12-12 22:13:57 +07:00
parent 6908e956e0
commit 8dbd54ac16
No known key found for this signature in database
GPG Key ID: C007F833B47313DA

View File

@ -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)