簡體   English   中英

將未讀電子郵件中的數據下載到單獨的文件Python中

[英]Download data from unread emails into separate files Python

我正在嘗試將未讀電子郵件中的數據下載到csv文件中,從某種意義上講,每個未讀電子郵件數據都將放入單獨的csv文件中。 我可以使用imaplab和電子郵件獲取未讀電子郵件的正文,但我不知道如何將它們保存到單獨的csv文件中,並用電子郵件正文的第一行命名它們。 到目前為止,這是我的代碼。

import imaplib
import email
server = imaplib.IMAP4_SSL('imap.gmail.com')
server.login('email@gmail.com', 'password')
server.select('[Gmail]/All Mail')
resp, items = server.search(None, "(UNSEEN)")
for mail in items[0].split():
    resp, data = server.fetch(mail, '(RFC822)')
    body = data[0][1]
    msg = email.message_from_string(body)
    content = msg.get_payload(decode=True)
    print content

謝謝。

解:

import email, imaplib, os

detach_dir = '.'

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login('email@gmail.com', 'password')
m.select("[Gmail]/All Mail") 

resp, items = m.search(None, "(UNSEEN)")
for mail in items[0].split():
    resp, data = m.fetch(mail, '(RFC822)')
    body = data[0][1]
    msg = email.message_from_string(body)
    content = msg.get_payload(decode=True)

    filename = content[2:7]
    counter = 1


    if not filename:
        filename = 'part-%03d%s' % (counter, 'bin')
        counter += 1

    file_path = os.path.join(detach_dir, filename)


    if not os.path.isfile(file_path) :

        fp = open(file_path+".csv", 'wb')
        fp.write(content)
        fp.close()
m.logout()
if not os.path.isfile(att_path) :
        for files in att_path:
            data = content.replace(" ", ",") #replaces if the delimiter is anything other than a ",". 
            fp = open(att_path+".csv", 'wb')
            fp.write(data)
            fp.close()

這將寫入正確分隔的文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM