0

i have python script like this to get email from my gmail. In some email i can get the csv file, but there are 1 email that got an error.

This is my script:

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()

there are error like this:

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

please help, thanks...

user3231429
  • 205
  • 1
  • 2
  • 13

2 Answers2

0

You have a case where there the filename variable is not being initialised. You need to create a default initialisation line above this line of code:

for i in range(emails):

Eg:

filename = None
Noel Evans
  • 8,113
  • 8
  • 48
  • 58
0

It's a variable scope issue.

In line 22 add filename = None.

The reason you're getting this error is because in line 47 the variable filename has not been declared. You declare it in line 43 inside the for loop and when the loop exits it's not there.

More info can be found here.

Community
  • 1
  • 1
alkar
  • 5,459
  • 7
  • 27
  • 43
  • Alkar, Yes, its working now. but in some emails even i dont add the filename=None it still retrieving the attachment.any idea?thanks – user3231429 Feb 19 '14 at 02:11