A
A
Alexey Sergeev2016-04-04 10:49:17
Django
Alexey Sergeev, 2016-04-04 10:49:17

How to properly attach images when sending an email?

Hello!
There is a code for sending reports from the site by e-mail.

def generate_mail():
    get_chart()
    today = timezone.now()
    peoples = Peoples.objects.filter(date=today, obj__is_active=True).values('obj__short_title').annotate(total_rab=Sum('rab'), total_itr=Sum('itr')).order_by('-total_rab')

    plain_text = get_template('email/email.txt')
    html_msg = get_template('email/email.html')

    d = Context({'peoples': peoples, 'today': today})

    subject, from_email, to = 'Проверка отчётов', 'some mailbox', ['list of mailboxes']
    text_content = plain_text.render(d)
    html_content = html_msg.render(d)

    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

The get_chart function itself makes a post request to a remote service and saves the png file to the media folder.
If you add a link to it in email.html as , then email clients block images from remote servers, you need to manually add the domain to the list of trusted ones, which is not very convenient. How to attach an image so that the picture is displayed at the beginning of the letter? <img src=''>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-04-04
@SergeevAI

Alternatively, encode to base64 and paste directly into the body of the email:

import base64
...
my_image = '<img src="data:image/jpg;base64,{im}" />'.format(im=base64.b64encode(instance.image.read()))
...
mail_html = """
        <html>
            <head></head>
            <body>
                <h4>Заголовок письма</h4>
                {img}
                ....
            </body>
        </html>
        """.format(img=my_image)

Next, encode the text of the letter in MIME and send it.

Y
Yura Khlyan, 2017-05-16
@MAGistr_MTM

https://djangosnippets.org/snippets/285/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question