Parse Multi-Part Email with Sub-parts using Python
<p>I am using this function to parse an email.  I am able to parse "simple" multi-part emails, but it produces an error (UnboundLocalError: local variable 'html' referenced before assignment) when the email defines multiple boundaries (sub-parts).  I would like the script to separate the text and html portions and return only the html portion (unless there is no html portion, return the text).</p>

<pre><code>def get_text(msg):
text = ""
if msg.is_multipart():
    for part in msg.get_payload():
        if part.get_content_charset() is None:
            charset = chardet.detect(str(part))['encoding']
        else:
            charset = part.get_content_charset()
        if part.get_content_type() == 'text/plain':
            text = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
        if part.get_content_type() == 'text/html':
            html = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
    if html is None:
        return text.strip()
    else:
        return html.strip()
else:
    text = unicode(msg.get_payload(decode=True),msg.get_content_charset(),'ignore').encode('utf8','replace')
    return text.strip()
</code></pre>
