from os.path import basename
from warnings import warn
from django.template import loader
from django.core.mail import EmailMultiAlternatives


def send_mail(subject, body_text, addr_from, recipient_list,
              fail_silently=False, attachments=None, html_message=None,
              **kwargs):
    """
    Sends a multipart email containing text and html versions.
    """
    msg = EmailMultiAlternatives(
        subject, body_text, addr_from, recipient_list,
        **kwargs
    )
    if html_message is not None:
        msg.attach_alternative(html_message, 'text/html')
    if attachments:
        for name, content in attachments:
            msg.attach(name, content)
    msg.send(fail_silently=fail_silently)


def send_mail_template(subject, template, addr_from, recipient_list,
                       fail_silently=False, attachments=None, context=None,
                       **kwargs):
    """
    Send email rendering text and html versions for the specified
    template name using the context dictionary passed in.
    """

    if context is None:
        context = {}

    # Loads a template passing in vars as context.
    def render(ext):
        name = "email_extras/%s.%s" % (template, ext)
        return loader.get_template(name).render(context)

    send_mail(subject, render("txt"), addr_from, recipient_list,
              fail_silently=fail_silently, attachments=attachments,
              html_message=render("html"),
              **kwargs)
