Example #1
0
def process_mailbox(M):
    rv, data = M.search(None, "ALL")
    if rv != "OK":
        print "Messagens não encontrada !"
        return

    for num in data[0].split():
        rv, data = M.fetch(num, "RFC822")
        if rv != "OK":
            print "Ocorreu algum problema ao recuperar a messagem"
            return

        msg = email.message_from_string(data[0][1])
        decode = email.header.decode_header(msg["Subject"])[0]
        subject = unicode(str(decode[0]).decode("utf-8")).encode("utf-8")
        print "Messagem %s: %s" % (num, subject)

        msg.set_default_type("text/html")
        #        email.encoders.encode_quopri(msg)

        a = {
            "msg.get_content_maintype() :": msg.get_content_maintype(),
            "msg.get_content_type() :": msg.get_content_type(),
            "msg.get_content_subtype() :": msg.get_content_subtype(),
            "msg.get_default_type() :": msg.get_default_type(),
            "msg.is_multipart() :": msg.is_multipart(),
            "msg.get_charsets() :": msg.get_charsets(),
        }

        # print type(a)
        for i in a:
            pass
            # print i, a.get(i)

        # for part in msg.walk():
        #    print part
        # Content-Transfer-Encoding
        # for i in msg.get_payload():
        #     print unicode(i).decode('utf-8').encode('utf-8')

        payload = msg.get_payload()
        body = extract_body(payload)

        print "##########################", body

        corpo = str(body).decode("utf-8").encode("utf-8").split("\x00")[0]

        import urllib2
        import urllib
        import binascii

        s = "BOLA=C3=83"
        # print urllib2.unquote(s)

        ss = "%C3%83".encode("cp1252")

        binascii.unhexlify(b"C383")

        z = body.replace("=", "%")

        urllib2.unquote(z)
        corpo = urllib.unquote_plus(z)
        print corpo

        # print corpo

        # from cStringIO import StringIO
        # from email.generator import Generator
        # fp = StringIO()
        # g = Generator(fp, mangle_from_=True, maxheaderlen=60)
        # g.flatten(msg)
        # text = fp.getvalue()

        # corpo = str(text).split('\x00')

        # print corpo

        # print 'Raw Date:', msg['Date']
        date_tuple = email.utils.parsedate_tz(msg["Date"])
        if date_tuple:
            local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
            # print "Data local:", \
            #    local_date.strftime("%a, %d %b %Y %H:%M:%S")

        msge = EmailMultiAlternatives(
            "TESTEAGORAVAI", corpo, "*****@*****.**", ["*****@*****.**", "*****@*****.**"]
        )
        msge.content_subtype = "html"
        msge.encoding = "UTF-8"
        msge.alternative_subtype = "html"
        msge.body.decode("utf-8").encode("utf-8")
        msge.attach_alternative(body, "text/html")

        msge.send()