2008-03-20

Export emails from Outlook

"""
Exports email address from MS Outlook from recent eemails
"""

from win32com.client import Dispatch, constants
import os.path

class Exporter(object):

app = None
emails = []

def __init__ (self):

self.app = Dispatch("Outlook.Application")
if self.app == None:
raise Exception, "Unable to create an Outlook application object"

def export_emails(self, foldername, outfile="email.csv", maxcount=1000):

emails = []
ns = self.app.GetNamespace("MAPI")
folders = ns.Folders.Item(1).Folders #Usually the users folders
folder = folders.Item(foldername)
cnt = len(folder.Items)
if cnt > maxcount:
cnt = maxcount
for i in range(1, cnt + 1):
item = folder.Items.Item(i)
print "Processing item %d" % i
self.export_from_field(item, "To")
self.export_from_field(item, "CC")

self.emails.sort()
emailfile = open(outfile, 'w')
for email in self.emails:
emailfile.write(email + "\n")
emailfile.close()

def export_from_field(self, item, fieldname, maxcount = 10):
if not hasattr(item, fieldname):
return
ms = getattr(item, fieldname).split(';')
if len(ms) > maxcount:
return
for m in ms:
parts = m.split(',')
if len(parts) <> 2:
continue
email = "%s_%s@intuit.com" % (parts[1].strip(), parts[0].strip())
if not email in self.emails:
self.emails.append(email)

def __del__ (self):

self.app = None
self.emails = None

def main ():
export = Exporter()
export.export_emails("InBox", "emails.csv", 1000)

if __name__ == "__main__":
main();