# coding: utf-8

from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings


class CustomEmailBackend(EmailBackend):

    def mutate_message(self, message):
        join = ", ".join
        orig_to = join(message.to)
        orig_cc = join(message.cc)
        orig_bcc = join(message.bcc)
        orig_template = "<br><br>Original to: %s<br>Original cc: %s<br>Original bcc: %s"

        message.body += orig_template % (orig_to, orig_cc, orig_bcc)
        message.to = [settings.ROUTE_ALL_MAIL_TO]
        message.cc = []
        message.bcc = []

        return message

    def send_messages(self, email_messages):
        if not email_messages:
            return

        if getattr(settings, 'ROUTE_ALL_MAIL_TO', False):
            email_messages = [self.mutate_message(m) for m in email_messages]

        return super(CustomEmailBackend, self).send_messages(email_messages)
