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...