2013-08-28 3 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()