Python错误从Gmail获取电子邮件

时间:2014-02-18 10:08:48

标签: python

我有这样的python脚本来从我的Gmail收到电子邮件。在某些电子邮件中,我可以获取csv文件,但有1封电子邮件出错。

这是我的剧本:

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

请帮助,谢谢...

2 个答案:

答案 0 :(得分:0)

你有一个没有初始化filename变量的情况。您需要在此代码行之上创建默认初始化行:

for i in range(emails):

例如:

filename = None

答案 1 :(得分:0)

这是一个可变范围问题。

在第22行添加filename = None

您收到此错误的原因是因为在第47行中尚未声明变量filename。你在for循环内的第43行声明它,当循环退出时它不在那里。

可以找到更多信息here