Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emailmultialternatives attach file and html content in django

Tags:

python

django

I tried to use the EmailMultiAlternatives to send an email in html and a text. I also want to include a file to this email.

But the later seems to erase my html content.

Here is my code :

msg = EmailMultiAlternatives(subject, html2text(html_content), 
list(email_from), list(email_to), 
attachments=((request.session['customer']+".txt.blowfish", 
request.session["customer"].content),)) 

msg.attach_alternative(html_content, "text/html") 

msg.send() 

I use the latest SVN revision I also tried using msg.attact() instead of attachments, same result!

The alternative text content is sent, but the html one is not. It only show the file.

Any clue would be much appreciated,

like image 396
arun Avatar asked Oct 26 '15 05:10

arun


1 Answers

I had the same issue!

The code I used to attach a file to a HTML email is:

email_dict = {}
email_dict['user'] = user                       

t = loader.get_template('emails/myemail.html')
html = t.render(Context(email_dict))

msg = EmailMultiAlternatives(subject='My Subject', 
                             body=html, 
                             from_email=settings.DEFAULT_FROM_EMAIL, 
                             to=['[email protected]'],) 

attachment = open('filepath', 'rb')
msg.attach('Name.txt', attachment.read(), 'text/csv')

msg.content_subtype = 'html'
msg.send()

So perhaps something like this could work for you:

msg = EmailMultiAlternatives(subject=subject, 
                             body=html2text(html_content), 
                             from_email=list(email_from), 
                             to=list(email_to))


attachment = open(request.session['customer']+".txt.blowfish", 'rb')
msg.attach('Name.txt.blowfish', attachment.read(), 'text/plain')

msg.content_subtype = 'html'
msg.send()

I hope this helps!

like image 78
tdsymonds Avatar answered Nov 10 '22 00:11

tdsymonds