#!/usr/bin/env python import getpass, imaplib, email, os from email import parser detach_dir = '/home/samba/shares/unique' M = imaplib.IMAP4('mail.ru') M.login('test@mail.ru', 'password') M.select() typ, data = M.search(None, 'FROM', '"test@mail.ru"') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headache for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: 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() M.close() M.logout()
Последняя версия моих экспериментов (с учетом подсказок людей):
#!/usr/bin/env python import getpass, imaplib, email, os from email import parser detach_dir = '/home/samba/shares/unique' detach_new = '/home/samba/shares/unique/%s/' % datetime.date.today() <----------------- M = imaplib.IMAP4('mail.ru') M.login('test@mail.ru', 'password') M.select() typ, data = M.search(None, 'ALL') <----------------- if data != ['']: <----------------- os.makedirs(detach_new) <----------------- for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headache for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: 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_new, 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() M.store(num, '+FLAGS', '\\Deleted') <----------------- M.close() M.logout()
Проблемы:
1.Если письмо без аттача, то оно не удаляется.
2.Если папка уже есть, то:
Traceback (most recent call last): File "./imap_detach_folder.py", line 19, in <module> os.makedirs(detach_new) File "/usr/lib/python2.5/os.py", line 171, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: '/home/samba/shares/unique/2014-03-31/'
Вторую проблему, конечно, можно решить, запуская скрипт раз в сутки. С первой пока не разобрался.
Принимаю любые советы по улучшению данного кода.