0
I need to send a request.FILES file from a File field as an attachment in the email. I’m following topics that teach this, but it’s not working.
Django from my project is 1.5
I’m doing it this way:
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 annex is the one that I will highlight:
msg.attach(files.name, files.read(), files.content_type)
Being in files I’m passing request.FILES[' annex']
The email is sent successfully, but in place of the body appears the read of the file:
JVBERi0xLjcKJeLjz9MKOCAwIG9iago8PAovRmlsdGVyIC9GbGF0ZURlY29kZQovTiAzCi9BbHRlcm5hdGUgL0RldmljZVJHQgovTGVuZ3RoIDI1OTMKPj4Kc3RyZWFtCnicnZZ3VFTXFofPvXd6oc0w dBh6r1IGEOkdpFdRGGYGG....
I have tried with attach_file, but the result is the same.
What is the type of
files
? A single object or a list/ICT?– Leonardo Pessoa
I tried it both ways. But this is very old, I can’t even remember how I resolved...
– Karl Zillner