I need to send a request.FILES file from a File field as an attachment in the email. I'm following a topic that teaches this, but it's not working out.
Django for my project is 1.5
I'm doing the following:
def send_templated_email(subject, email_template_name, email_context, recipients,
sender=None, bcc=None, reply_to=None, fail_silently=True, files=None):
from django.core.mail import EmailMultiAlternatives
from django.template import loader, Context
from django.utils.html import strip_tags
c = Context(email_context)
if not sender:
sender = settings.DEFAULT_FROM_EMAIL
template = loader.get_template(email_template_name)
text_part = strip_tags(template.render(c))
html_part = template.render(c)
if reply_to:
headers = {'Reply-To': reply_to}
else:
headers = {}
if type(recipients) == str:
if recipients.find(','):
recipients = recipients.split(',')
elif type(recipients) != list:
recipients = [recipients,]
msg = EmailMultiAlternatives(subject,
text_part,
sender,
recipients,
bcc=bcc,
headers=headers)
# if files:
# if type(files) != list:
# files = [files,]
# for f in files:
# msg.attach_file(f)
if files:
msg.attach(files.name, files.read(), files.content_type)
msg.attach_alternative(html_part, "text/html")
return msg.send(fail_silently)
In practice the part of the attachment is this that I will highlight:
msg.attach(files.name, files.read(), files.content_type)
Being in files I'm passing request.FILES ['attachment']
The email is sent successfully, however in the place of the body the read of the file appears:
JVBERi0xLjcKJeLjz9MKOCAwIG9iago8PAovRmlsdGVyIC9GbGF0ZURlY29kZQovTiAzCi9BbHRlcm5hdGUgL0RldmljZVJHQgovTGVuZ3RoIDI1OTMKPj4Kc3RyZWFtCnicnZZ3VFTXFofPvXd6oc0w dBh6r1IGEOkdpFdRGGYGG....
I've also tried attach_file, but the result is the same.