Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Last active May 14, 2017 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Lewiscowles1986/111d1f9600fb6c768162 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/111d1f9600fb6c768162 to your computer and use it in GitHub Desktop.
# 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