Die Überschrift sagt eigentlich schon alles. Das Code Snippet dient dazu von einem IMAP Server Mails zu laden und mit dem Payload Dinge anzustellen.

#!/usr/bin/env python

import imaplib
import sys
import email
import re
import email.header
import base64
from HTMLParser import HTMLParser

username = "blah@blah.de"
password = "xxxxxx"

imap_rz1 = "imap.xxx.de"
imap_rz2 = "imap-rz2.xxxxx.de"


class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()




# Try primary server
try:
    M = imaplib.IMAP4(imap_rz1)

except:

    sys.stderr.write("Try second server, primary not reachable.\n")
    # Try secondary server
    try:
        M = imaplib.IMAP4(imap_rz2)

    except:
        sys.stderr.write("Error no connection possible.\n")
        sys.exit(1)

# Try to Login
try:
    M.login(username, password)

except:
    sys.stderr.write("Error login.\n")
    sys.exit(1)

# DATA
M.select()
typ, data = M.search(None, 'ALL')

for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')

    #### print 'Message %s\n%s\n' % (num, data[0][1])
    msg = email.message_from_string(data[0][1])
    hdr = email.header.make_header(email.header.decode_header(msg['Subject']))

    if msg.is_multipart():
        print "Multipart Mail"
        for payload in msg.get_payload():
            print payload.get_payload()
    else:

        enc = msg['Content-Transfer-Encoding']

        if enc == "base64":
            dirty = msg.get_payload()
            payload = base64.decodestring(dirty)
            print payload
            #print strip_tags(payload)
            pmail = parse_mail(mailcontent=strip_tags(payload).rstrip().lstrip().splitlines())
        else:
            print msg.get_payload()
            #print strip_tags(msg.get_payload())
            pmail = parse_mail(mailcontent=strip_tags(msg.get_payload()).rstrip().lstrip().splitlines())
            
    # Set to deleted
    M.store(num, '+FLAGS', '\\Deleted')

# Delete permanently
M.expunge()
# Close current mailbox
M.close()
# Logout
M.logout()

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*