2014-02-18 42 views
0

我有這樣的Python腳本來從我的Gmail郵件。在某些電子郵件中,我可以獲得csv文件,但有一封電子郵件發生錯誤。從Python錯誤取回電子郵件

這是我的腳本:

import poplib 
import email 
import os 

detach_dir = '.' # directory where to save attachments (default: current) 

class GmailTest(object): 
def __init__(self): 
    self.savedir="/tmp" 

def test_save_attach(self): 
    self.connection = poplib.POP3_SSL('pop.gmail.com', 995) 
    self.connection.set_debuglevel(1) 
    self.connection.user("email.google") 
    self.connection.pass_("Password") 

    emails, total_bytes = self.connection.stat() 
    print("{0} emails in the inbox, {1} bytes total".format(emails, total_bytes)) 
    # return in format: (response, ['mesg_num octets', ...], octets) 
    msg_list = self.connection.list() 
    print(msg_list) 

    # messages processing 
    for i in range(emails): 

     # return in format: (response, ['line', ...], octets) 
     response = self.connection.retr(i+1) 
     raw_message = response[1] 

     str_message = email.message_from_string('\n'.join(raw_message)) 

     # save attach 
     for part in str_message.walk(): 
      print(part.get_content_type()) 

      if part.get_content_maintype() == 'multipart': 
       continue 

      if part.get('Content-Disposition') is None: 
       print("no content dispo") 
       continue 

      filename = part.get_filename() 
    counter = 1 

    # if there is no filename, we create one with a counter to avoid duplicates 
    if not filename: 
     filename = 'part-%03d%s' % (counter, 'bin') 
     counter += 1 

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

    #Check if its already there 
    if not os.path.isfile(att_path) : 
     # finally write the stuff 
     fp = open(att_path, 'wb') 
     fp.write(part.get_payload(decode=True)) 
     fp.close() 
      # if not(filename): filename = "test.txt" 
      # print(filename) 

      # fp = open(os.path.join(self.savedir, filename), 'wb') 
      # fp.write(part.get_payload(decode=1)) 
      # fp.close 

    #I exit here instead of pop3lib quit to make sure the message doesn't get removed in gmail 
    import sys 
    sys.exit(0) 

d=GmailTest() 
d.test_save_attach() 

有錯誤這樣的:

Traceback (most recent call last): 
File "getmail.py", line 71, in <module> 
d.test_save_attach() 
File "getmail.py", line 47, in test_save_attach 
if not filename: 
UnboundLocalError: local variable 'filename' referenced before assignment 

請幫忙,謝謝...

回答

0

這是一個變量範圍的問題。

在第22行添加filename = None

你得到這個錯誤的原因是因爲在第47行中變量filename還沒有被聲明。你在for循環內的第43行聲明它,當循環退出時它不在那裏。

更多信息可查詢here

+0

阿爾卡,是的,現在工作。但在一些電子郵件中,即使我不添加文件名=無它仍然檢索attachment.any的想法?謝謝 – user3231429

0

那裏的文件名變量是你有一個案例沒有被初始化。你需要創建一個默認初始化行上面這行代碼:

for i in range(emails): 

如:

filename = None