1

I am trying to send a logo with the email and have it appear in the HTML part of the email. I am building my email like this:

    mail_subject = _("Subject of email %s" %
                     self.get_company_display())
    from_email = "test@test.com"

    message = EmailMultiAlternatives(mail_subject, mail_txt, from_email,
                                     ['destination@email.com'])
    message.attach_alternative(mail_html, 'text/html')
    message.attach('logo.png', static('myapp/images/logo.png'))
    message.send()

And in my mail template I have:

<img src="cid:logo.png">

I receive the email but the image doesn't appear in the email. In fact, the email does not appear to have the image as an attachment.

Working on Python 3.4, Django 1.8.4 and sending the mails through Postfix installed on the same machine Django is running.

Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25

2 Answers2

2

The EmailMessage.attach method expects to be passed the content of the file not its path, what you are actually doing is attaching the string returned by static('myapp/images/logo.png') to the message.

Use EmailMessage.attach_file instead (EmailMessage reference).

aumo
  • 5,344
  • 22
  • 25
-1

The whole purpose of yagmail (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs.

Please try the following code:

import yagmail
yag = yagmail.SMTP(from_add, password) # add host="" and port=
contents = ['See my attachment below', '/home/static/images/logo.png']
yag.send(contents = contents)

Notice the magic here: contents is a list, where an item equal to a file path will automatically be loaded, mimetype guessed, and attached.

There's a lot more magic involved, such as easy to embed images, passwordless scripts, usernameless scripts, easy aliases, smart defaults (notice I omitted the to and subject arguments?) and much more. I advise/encourage you to read its github page :-). Feel free to raise issues or add feature requests!

You can get yagmail by using pip to install it:

pip install yagmail # Python 2
pip3 install yagmail # Python 3
PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
  • Thanks, but I'm not really looking for an SMTP client, let alone a Gmail client. Like I said, the tool uses a local Postfix installation. Having said that, your tool looks like it could be very useful! Just not in this particular case. – Jorick Spitzen Aug 27 '15 at 14:11
  • Don't let the name fool you; it can actually use any host. It's just that the host/port are gmail defaults. Setting the host and port to the current info would allow it to work, as long as it is using SMTP (which [this django/postfix question](http://stackoverflow.com/a/28143166/1575066) described. Good luck! – PascalVKooten Aug 27 '15 at 14:18