from __future__ import absolute_import import os.path import re from email.MIMEBase import MIMEBase from django.conf import settings from django.core.mail import EmailMultiAlternatives, SafeMIMEMultipart class EmailMultiRelated(EmailMultiAlternatives): """ A version of EmailMessage that makes it easy to send multipart/related messages. For example, including text and HTML versions with inline images. @see https://djangosnippets.org/snippets/2215/ """ related_subtype = 'related' def __init__(self, *args, **kwargs): # self.related_ids = [] self.related_attachments = [] return super(EmailMultiRelated, self).__init__(*args, **kwargs) def attach_related(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. """ if isinstance(filename, MIMEBase): assert content == mimetype == None self.related_attachments.append(filename) else: assert content is not None self.related_attachments.append((filename, content, mimetype)) def attach_related_file(self, path, mimetype=None): """Attaches a file from the filesystem.""" filename = os.path.basename(path) content = open(path, 'rb').read() self.attach_related(filename, content, mimetype) def _create_message(self, msg): return self._create_attachments(self._create_related_attachments(self._create_alternatives(msg))) def _create_alternatives(self, msg): for i, (content, mimetype) in enumerate(self.alternatives): if mimetype == 'text/html': for related_attachment in self.related_attachments: if isinstance(related_attachment, MIMEBase): content_id = related_attachment.get('Content-ID') content = re.sub(r'(?' % filename) return attachment