importing gmail text content to a text file with python returns nothing

不羁的心 提交于 2019-12-12 02:18:59

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22590945/importing-gmail-text-content-to-a-text-file-with-python-returns-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!