Friday, 6 March 2015

How to extract email ids from your gmail account using a python script

Recently a friend of mine asked me to give him all the email ids that i have. Post the usual discussion of 'i will not spam them, it's research purpose, ... is what i am working on' i agreed to give him the list. He sent me a link to some 3rd part service which i was suppose to authenticate to so he can get the list of mail id's. While he is not a techie, i am. So agreeing to an o-auth with some random 3rd party website does not sound like a good idea to me. Thus i mailed him that i will not authenticate a 3rd party app with o-auth but i will give him the list of mail ids and i will extract it myself. He didn't mind it so i set to work:

I found a simple program online :


import imaplib, email

def split_mail_id(email_id):
    #split an address list into list of tuples of (name, address)
    if not(email_id): return []
    out_queue = True
    cut = -1
    result = []
    for i in range(len(email_id)):
        if email_id[i]=='"': out_queue = not(out_queue)
        if out_queue and email_id[i]==',':
            result.append(email.utils.parseaddr(email_id[cut+1:i]))
            cut = i
    result.append(email.utils.parseaddr(email_id[cut+1:i+1]))
    return result

user_id = "<email>"
password = "<app_password>" #at the bottom of the page we explain how to get this password

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user_id, password)
mail.select("INBOX")
result, data = mail.search(None,"ALL")
ids = data[0].split()
msgs = mail.fetch(','.join(ids),'(BODY.PEEK[HEADER])')[1][0::2]
addresses = []
for x, msg in msgs:
    msgobj = email.message_from_string(msg)
    addresses.extend(split_mail_id(msgobj['to']))
    addresses.extend(split_mail_id(msgobj['from']))
    addresses.extend(split_mail_id(msgobj['cc']))

output_file = open('mail_ids.txt','w')
for address in addresses:
    output_file.write(address[1] + "\n")
output_file.close()


Now, How to get app specific gmail password:

goto : https://myaccount.google.com/

and select App passwords or direct click this link: 

https://security.google.com/settings/security/apppasswords

There select "other". Enter a name like mail_ids and generate a password.


this is a google app password. You can use this password to access your gmail account from any app.


Finally my friend got all the mail ids in a .txt file. He is happy and i am happy that i didn't had to authenticate a 3rd party app with my gmail.

Peace Out.

1 comment:

  1. The article is quite good, we understand the work well. We are thankful for that. Good article, check also thos blog thank you.
    New Exploit Steals mac passwords keychain

    ReplyDelete