import email
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase

class HTMLEmail(object):
    """ provide a nice high-level api for generating multipart emails

        this uses email.MimeMultipart to generate emails containing both
        an HTML and a text body (and no other parts)
    """

    def __init__(self, fro, to, subject, html, text):
        self.fro = fro
        self.to = to
        self.subject = subject
        self.html = html
        self.text = text

    def serialize(self):
        msg = MIMEMultipart()
        msg.set_type('multipart/alternative')
        msg['Subject'] = self.subject
        msg['To'] = self.to
        msg['From'] = self.fro
        msg.preamble = self.text

        msg.set_payload([
            self._create_attachment('text/plain; charset=UTF-8', self.text),
            self._create_attachment('text/html; charset=UTF-8', self.html)])

        return msg.as_string()

    def _create_attachment(self, ctype, body):
        maintype, subtype = ctype.split('/', 1)
        if ';' in subtype:
            subtype = subtype.split(';')[0]
        at = MIMEBase(maintype, subtype)
        at.set_type(ctype)
        at.set_payload(body)
        return at

