Last active
August 29, 2015 14:22
-
-
Save chrisdev/054e262d6db2a2b4e5bc to your computer and use it in GitHub Desktop.
Extract email addresses from email messages via IMAPP
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
import imaplib, email | |
import getpass, imaplib, email, sets | |
def split_addrs(s): | |
#split an address list into list of tuples of (name,address) | |
if not(s): return [] | |
outQ = True | |
cut = -1 | |
res = [] | |
for i in range(len(s)): | |
if s[i]=='"': outQ = not(outQ) | |
if outQ and s[i]==',': | |
res.append(email.utils.parseaddr(s[cut+1:i])) | |
cut=i | |
res.append(email.utils.parseaddr(s[cut+1:i+1])) | |
return res | |
def get_addresses( name, password, folder=None): | |
if folder: | |
folder = folder | |
else: | |
folder = "INBOX" | |
mail=imaplib.IMAP4_SSL('imap.gmail.com') | |
mail.login( name , password ) | |
print "In email account, accessing \"%s\" folder...\n" % (folder) | |
mail.select(folder) | |
result,data=mail.search(None,"ALL") | |
ids=data[0].split()[-10:] | |
print "Processing %d emails...\n" % ( len(ids) ) | |
msgs = mail.fetch(','.join(ids),'(BODY.PEEK[HEADER])')[1][0::2] | |
addr=[] | |
for x,msg in msgs: | |
msgobj = email.message_from_string(msg) | |
addr.extend(split_addrs(msgobj['to'])) | |
addr.extend(split_addrs(msgobj['from'])) | |
addr.extend(split_addrs(msgobj['cc'])) | |
mail.close() | |
mail.logout() | |
addr_set = set(addr) | |
print "Fetched and writing %d unique name and emails to scraped_email.txt...\n" % ( len(addr_set) ) | |
f = open('scraped_emails.txt', 'w') | |
for each in addr_set: | |
name, address = each | |
#print "%s, %s" % (name, address) | |
f.write("%s, %s\n" % (name, address)) | |
f.close() | |
print "Done" | |
if __name__ == '__main__': | |
email_address = raw_input('Enter your email: ') | |
print "Username: %s" % ( email_address ) | |
get_addresses( email_address, getpass.getpass()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be careful if you use MailApp on OSX and you use this script with an email account that you have not set up in MailApp. You may find that MailApp will not sync your messages.