Search code examples
djangopdfemail-attachments

In EmailMultiAlternatives attach and attach_alternative both at time is not working


from django.core.mail import EmailMultiAlternatives
subject, from_email, to,bcc = 
request.POST['sub'],'fulfillment@***.com', lead.mailid,email_ccaddress
msg = EmailMultiAlternatives(subject, "", from_email, [to])
filepdf = open("Plan.pdf",'rb').read()
msg.attach("Plan.pdf",filepdf,'application/pdf')
msg.attach_alternative(request.POST['bodyofmail'], "text/html")
msg.content_subtype = 'html'
msg.send()

using Django 1.11.3 python3 EmailMultiAlternatives

Individually both are working fine but once we run this code with attachment and attach_alternative HTML only pdf attachment is receiving in an email server


Solution

  • The problem is that you are setting content_subtype on the message, and then attaching a separate text/html alternative. Doing both of these together doesn't make sense - it means that the mail client receives two text/html alternatives in the email and doesn't know which to render. It will just use the first.

    Either remove the content_subtype, or put your html body in the body argument and drop the attach_alternative. In the latter case you can stop using EmailMultiAlternative and just use the EmailMessage class.