2013-08-28 65 views
6

我想從電子郵件附件,並將其保存到特定的文件夾與原始文件名。該電子郵件是非常基本的,除附件外沒有多少內容。該文件是一個csv文件,每個電子郵件只有一個。這是我迄今爲止,但我是新來的,我不知道如何繼續。如果有幫助,這是使用Outlook。任何幫助表示讚賞。如何從電子郵件CSV附件,並將其保存

import imaplib 
import email 


mail=imaplib.IMAP4('mailserver.com') 
mail.login("username", "password") 
mail.select("DetReport") 

typ, msgs = mail.uid('Search', None, '(SUBJECT "Detection")') 
msgs = msgs[0].split() 

for emailid in msgs: 
    resp, data = mail.fetch(emailid, "(RFC822)") 
    email_body = data[0][1] 
    m = email.message_from_string(email_body) 


    message=m.get_content_maintype() 

僅供參考,當我運行message=m.get_content_maintype()它說,這是文本。

回答

11

我環顧四周,嘗試了更多的東西。這些: Downloading multiple attachments using imaplibHow do I download only unread attachments from a specific gmail label?有了答案,一旦我發揮它一點點。該工作

代碼:

import imaplib 
import email 
import os 

svdir = 'c:/downloads' 


mail=imaplib.IMAP4('mailserver') 
mail.login("username","password") 
mail.select("DetReport") 

typ, msgs = mail.search(None, '(SUBJECT "Detection")') 
msgs = msgs[0].split() 

for emailid in msgs: 
    resp, data = mail.fetch(emailid, "(RFC822)") 
    email_body = data[0][1] 
    m = email.message_from_string(email_body) 


    if m.get_content_maintype() != 'multipart': 
    continue 

    for part in m.walk(): 
     if part.get_content_maintype() == 'multipart': 
      continue 
     if part.get('Content-Disposition') is None: 
      continue 

     filename=part.get_filename() 
     if filename is not None: 
      sv_path = os.path.join(svdir, filename) 
      if not os.path.isfile(sv_path): 
       print sv_path  
       fp = open(sv_path, 'wb') 
       fp.write(part.get_payload(decode=True)) 
       fp.close() 

POP3:

import poplib 
import email 

server = poplib.POP3(pop_server) 
server.user(user) 
server.pass_(pass) 

# get amount of new mails and get the emails for them 
messages = [server.retr(n+1) for n in range(len(server.list()[1]))] 

# for every message get the second item (the message itself) and convert it to a string with \n; then create python email with the strings 
emails = [email.message_from_string('\n'.join(message[1])) for message in messages] 

for mail in emails: 
    # check for attachment; 
    for part in mail.walk(): 
     if not mail.is_multipart(): 
      continue 
     if mail.get('Content-Disposition'): 
      continue 
     file_name = part.get_filename() 
     # check if email park has filename --> attachment part 
     if file_name: 
      file = open(file_name,'w+') 
      file.write(part.get_payload(decode=True)) 
      file.close() 
相關問題