Last active
May 14, 2017 17:48
-
-
Save Lewiscowles1986/111d1f9600fb6c768162 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Email SQLite Backup Hack | |
# 2015 | |
# Lewis Cowles | |
# Nasty Python 2.7 Compatible E-Mail Backup (Once done) | |
import imaplib, email, sqlite3 | |
from email.utils import * | |
from datetime import datetime | |
# Setup DB | |
conn = sqlite3.connect('email.sqlite', detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) | |
db = conn.cursor() | |
# Setup IMap | |
M = imaplib.IMAP4('hostname',143) | |
M.login('username', 'password') | |
M.select() | |
typ, data = M.search(None, 'ALL') | |
# Now for some action | |
for num in data[0].split(): | |
typ, mdata = M.fetch(num, '(RFC822)') | |
tmp = {} | |
for response_part in mdata: | |
if isinstance(response_part, tuple): | |
#print response_part[0] | |
msg = email.message_from_string(response_part[1]) | |
for header in [ 'subject', 'to', 'cc','bcc', 'from' ]: | |
tmp[ header.lower() ] = msg[header] | |
tmp['date'] = email.utils.parsedate(msg['date']) | |
tmp['date'] = datetime(*(tmp['date'][0:5])) | |
print( tmp['date'] ) | |
tmp['body'] = msg.get_payload(decode=True) | |
tmp['import'] = response_part[0] | |
try: | |
db.execute("INSERT INTO email_tmp (subject,_to,cc,bcc,_from,_date,body,import) VALUES (:subject,:to,:cc,:bcc,:from,:date,:body,:import)",tmp) | |
except: | |
print "\nError Inserting ", response_part[0] ,"...\n" | |
conn.commit() | |
print "processed", num, "messages" | |
M.close() | |
M.logout() | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment