Question

I was looking for a solution to get all my text messages/content (not attachments) in my gmail's email-account to a text file and I found a piece of code which promises to do so. I have python 3.4 and 2.7 both installed on win 7. I know php a bit but python I am zero. Right now, I have the code copied into a notepad text and saved it as test.py. Here is the complete code.

import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myemailid@gmail.com', 'mypassword')
mail.list() 
mail.select('inbox')

result, data = mail.uid('search', None, "ALL")
i = len(data[0].split())
for x in range(i):
    latest_email_uid = data[0].split()[x]
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
    raw_email = email_data[0][1]

    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)
for part in email_message.walk():
    if part.get_content_type() == "text/plain":
        body = part.get_payload(decode=True)
        save_string = r"F:\result\email_" + str(x) + ".txt"
        myfile = open(save_string, 'a')
        myfile.write(body.decode('utf-8'))
        myfile.close()
    else:
        continue

ISSUE : The code when run gives nothing in return.

UPDATE : Actually I have been going through a lot of threads here. Closest to what I am asking are here and here but no one has a unified answer and the solutions are scattered in bits and pieces, or it is too specific so it is very difficult for me to make sense out of it. Trust me, I am testing and trying. Even a Similar question remains unanswered here.

Was it helpful?

Solution

For those who may find it useful. This script will run fine on Python 3.4 with these changes.

save_string = "F:\\result\\email_" + str(x) + ".txt"

myfile.write(str(body)).

Just change the directory and the folder name according to your need. Thanks to the original code provider.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top