Example #1
0
def createmail(subject, htmltemplate='',texttemplate='', context={}, attachments=[]):
    """
    if you want to use Django template system:
       use `context` as template context (dict)
       and define `htmltemplate` and optionally `texttemplate` variables.
    """

    htmltemplate, images = src2cid(htmltemplate)

    html = Template(htmltemplate).render(Context(context))
    text = Template(texttemplate).render(Context(context))
    subject = Template(subject).render(Context(context))

    # creating mail object
    msg = EmailMultiAlternatives(subject='', body=text, from_email=None, to=None)
    msg.attach_alternative(html, "text/html")

    for img_path, img_cid in images:
        try:
            fp = open(os.path.join(settings.MEDIA_ROOT,img_path, 'rb'))
            cnt = fp.read()
            fp.close()
            msg.attach_image(cnt, img_cid)
        except:
            pass
    for attachment in attachments:
        msg.attach_file(attachment)
    return msg