Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send email with inline images asynchronously #462

Open
DenisBotev opened this issue Jan 15, 2024 · 0 comments
Open

Send email with inline images asynchronously #462

DenisBotev opened this issue Jan 15, 2024 · 0 comments

Comments

@DenisBotev
Copy link

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(
    '[email protected]', 
    '[email protected]',
    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant