在python中保存电子邮件

时间:2016-10-27 14:50:45

标签: python email gmail

我正在尝试以ELM格式保存我的Gmail帐户中的电子邮件。我正在努力保留尽可能多的信息(To,From,CC,附件等),因为我希望将其转换为PST格式,并在将来需要时重新创建我的Outlook。我只想出如何将电子邮件的内容保存到ELM文件中,但我无法弄清楚如何使用此电子邮件库保存其他电子邮件信息。

import imaplib
import email

#Login
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email', 'pswd')


mail.list() # Lists all labels in GMail
mail.select('inbox') # Connected to inbox



result, data = mail.search(None, "ALL")
ids = data[0] 
id_list = ids.split() 
i = len(data[0].split())
for x in range(i):
    latest_email_id = id_list[x] #get the latest
    result, data = result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
    raw_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": # ignore attachments/html
      body = part.get_payload(decode=True)

      save_string = str(r"C:\Users\Millar\Desktop\SavedEmailsTest\Dumpgmailemail_" + str(x) + ".eml")

      myfile = open(save_string, 'a')
      myfile.write(body.decode('utf-8'))
      myfile.close()
     else:
      continue

0 个答案:

没有答案