I’m using the EmailMultiAlternatives class to send text and html mails with django.
While testing with some dummy code, I wanted to add an image with some text.
msg = EmailMultiAlternatives('My subject','some text here', 'from@domain.com', ['to@my_domain.com'])
msg.attach_alternative('<p>here is what I was talking about</p> <img src="logo.png" alt="logo_here" /> <div>You see???</div>', 'text/html')
msg.attach_file('/var/my_site/static/images/logo.png')
msg.send()
The problem is that on the email client the image is not displaying…
Looking at the raw email, I found this:
--===============1013820581535380480==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
<p>here is what I was talking about</p> <img src=3D"logo.png" alt=3D"logo_h=
ere" /> <div>You see???</div>
--===============1013820581535380480==--
Does anybody have an idea of what I’m doing wrong??
Thanks!
Edit: I could manage to embed an image into the html mail. It seems that the EmailMultiAlternatives has an attach method that can accept an MimeImage object. Actually it can accept anything that inherits from MimeBase.
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
mimeImage = MimeImage(fp.read())
mimeImage.add_header('Content-ID', '<logo.png>')
msg.attach(mimeImage)
msg.send()
This is only a partial solution. When I create an email in thunderbird and embed an image (it’s visible when I view the message), the source looks like this:
then the contents of the image follow. The URL in the image tag needs to be the Content-ID of the attached image. I’m just not sure how to specify that.
EDIT: It seems you can do it with the email module in the standard library instead of Django’s EmailMultiAlternatives. See here: http://code.activestate.com/recipes/473810/