Code: Alles auswählen
import imaplib
import re
import email
import quopri
import MySQLdb
from email.header import decode_header
def strip_tags(value):
"Return the given HTML with all tags stripped."
return re.sub(r'<[^>]*?>', '', value)
im = imaplib.IMAP4_SSL("xxx.xxx.xxx")
im.login("xxx+xxx-xxxx.xxx", "xxxxxxx")
konto = 'office'
print "Vorhandene Mailboxen:"
for mb in im.list()[1]:
name = mb.split("\".\"")[-1]
name = name.strip(" \"")
print "%s" % name
im.select(name)
status, daten = im.search(None, "ALL")
for msg_id in im.search(None, 'ALL')[1][0].split():
msg = email.message_from_string(im.fetch(msg_id, '(RFC822)')[1][0][1])
mailenc = msg.get_content_charset()
if mailenc is None:
mailenc = "ISO-8859-1"
FROM = str(msg['From'].decode(mailenc).encode('ISO-8859-1'))
TO = str(msg['To'].decode(mailenc).encode('ISO-8859-1'))
tmp = decode_header(msg['Subject'])
mailenc = tmp[0][1]
if mailenc is None:
mailenc = "ISO-8859-1"
SUBJECT = str(tmp[0][0].decode(mailenc).encode('ISO-8859-1'))
DATE = str(msg['Date'])
MSGID = str(msg['Message-Id'])
tmp = ""
if msg.is_multipart():
for part in msg.get_payload():
txtenc = part.get('content-transfer-encoding')
mailenc = part.get_content_charset()
if mailenc is None:
mailenc = "ISO-8859-1"
if txtenc == "quoted-printable":
text = quopri.decodestring(part.get_payload())
text = str(text.decode('UTF-8').encode('ISO-8859-1'))
elif txtenc == "base64":
text = ""
else:
text = str(text.decode(mailenc).encode('ISO-8859-1'))
tmp = tmp + "\n" + text
text = tmp
else:
text = msg.get_payload(decode=True)
text = text.decode(mailenc).encode('ISO-8859-1')
conn = MySQLdb.connect("localhost", "root", "", "mailserver")
cursor = conn.cursor()
cursor.execute("SELECT id FROM mails WHERE msg_id=\"%s\"", (MSGID))
zz = 0
for row in cursor:
zz = zz + 1
if zz < 1:
cursor.execute("INSERT INTO mails VALUES(\"\", %s, %s, %s, %s, %s, %s)", (MSGID, FROM, TO, DATE, SUBJECT, text))
print "MsgID ", MSGID, " ... gespeichert \n"
else:
print "MsgID ", MSGID, " ... ausgelassen \n"
im.close()
im.logout()