Send mail with Inline images in Django using django-mail-queue

809 views Asked by At

I want to send inline promotional images in mail content like e-commerce websites sends in their mail. For mailing I have used django-mail-queue package, but I don't know it is supported in it or not. I would appreciate if you help me out.

Another concern is that server on which django application hosted is not accessible by email receiver, so I can't simply provide image url in django template.

1

There are 1 answers

6
Prakhar Trivedi On

You can send the images as Context and then pass them as the template vairable. Like this:

from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template

def some_view(request):
    template = get_template('myapp/email.html')
    image_url ="static/images/sample_image.jpg"
    context = Context({'user': user, 'other_info': info,'image_url':image_url})
    content = template.render(context)
    if not user.email:
        raise BadHeaderError('No email address given for {0}'.format(user))
    msg = EmailMessage(subject, content, from, to=[user.email,])
    msg.send()

And then, in template myapp/email.html ,use this :

<img src="{{ image_url }}" ...>

And if the server side images are not accessible to email receiver, you can send the images as attachment files but that won't serve the purpose, for actually displaying an image, img src needs a source url where the actual image is stored.

You can host your images on any other image hosting website and put that URL in image_url variable.