Emails sent using EmailMultiAlternatives are not sent through Celery, but through the standard Django backend. At least not in my case - perhaps I missed something. Either way, I found the following workaround to attach an inline image to mail.send which might be useful to others:
We initially follow the instructions in the README up until the initialization of the EmailMultiAlternatives.
Then, we instead create a dummy EmailMultiAlternatives instance and attach the image like in the tutorial:
dummy_multialt = EmailMultiAlternatives(subject, body, from_email, [to_email])
template = get_template('email-template-name.html', using='post_office')
context = {...}
html = template.render(context)
dummy_multialt.attach_alternative(html, 'text/html')
template.attach_related(dummy_multialt)
Then, we get the newly attached image using a somewhat ugly solution:
inline_image = template.template._attached_images[0] # in case we attached just one image
inline_image_headers = dict(inline_image.__dict__["_headers"]) # cast image headers to a dict in order to plug them directly later
inline_image_cid = inline_image_headers["Content-ID"].replace("<", "").replace(">", "")
and finally:
mail.send(
'recipient@example.com',
'from@example.com',
subject='My email',
message='Hi there!',
html_message=html,
attachments={
inline_image_cid: {
"file": ContentFile(inline_image.get_payload()),
"mimetype": "image/png",
"headers": inline_image_headers
}
}
)
I'm sure there must be a cleaner way, but I'm not really experienced with MIME objects.
Currently I can't think of a way to include this painlessly into the codebase, this is why I'm posting it as an Issue.
Emails sent using
EmailMultiAlternativesare not sent through Celery, but through the standard Django backend. At least not in my case - perhaps I missed something. Either way, I found the following workaround to attach an inline image tomail.sendwhich might be useful to others:We initially follow the instructions in the README up until the initialization of the
EmailMultiAlternatives.Then, we instead create a dummy
EmailMultiAlternativesinstance and attach the image like in the tutorial:Then, we get the newly attached image using a somewhat ugly solution:
and finally:
I'm sure there must be a cleaner way, but I'm not really experienced with MIME objects.
Currently I can't think of a way to include this painlessly into the codebase, this is why I'm posting it as an Issue.