Skip to content

Instantly share code, notes, and snippets.

@maxpoletaev
Last active December 17, 2019 15:04
Show Gist options
  • Save maxpoletaev/e735cd597e5a6c039a8b5f697ad5ac8e to your computer and use it in GitHub Desktop.
Save maxpoletaev/e735cd597e5a6c039a8b5f697ad5ac8e to your computer and use it in GitHub Desktop.
import os
from email.mime.image import MIMEImage
from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import get_connection, EmailMultiAlternatives
def make_message(
subject,
body,
to,
images=None,
attachments=None,
connection=None,
reply_to=None,
from_email=settings.DEFAULT_FROM_EMAIL,
):
msg = EmailMultiAlternatives(
subject=subject,
body=body,
from_email=from_email,
to=to,
connection=connection,
reply_to=reply_to,
)
if images:
msg.mixed_subtype = "related"
for image_path in images:
content_id = os.path.basename(image_path)
with open(image_path, "rb") as fp:
image_data = fp.read()
image = MIMEImage(image_data)
image.add_header("Content-ID", "<{}>".format(content_id))
msg.attach(image)
if attachments:
for filename, path in attachments:
with open(path, "rb") as fp:
content = fp.read()
msg.attach(filename, content)
msg.content_subtype = "html"
return msg
def send_html_email(
subject,
template,
to,
context=None,
reply_to=None,
images=None,
attachments=None,
fail_silently=False,
):
connection = get_connection(fail_silently=fail_silently)
body = render_to_string(template, context)
messages = []
for recipient in to:
msg = make_message(
subject=subject,
body=body,
to=[recipient],
connection=connection,
images=images,
attachments=attachments,
reply_to=reply_to,
)
messages.append(msg)
connection.send_messages(messages)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment