Форум сайта python.su
0
На просторах интернета нашел такой скрипт:
#!/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()
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/'
Отредактировано kolin_k (Март 31, 2014 17:13:48)
Офлайн
36
У Вас отступы не правильно расставлены :(
kolin_kА можно проверять существование папки:
Вторую проблему, конечно, можно решить, запуская скрипт раз в сутки
if not os.path.isdir(detach_new): os.makedirs(detach_new)
kolin_kНужно слегка изменить логику:
С первой пока не разобрался
#Check if any attachments at all if mail.get_content_maintype() == 'multipart': # здесь обрабатываем письмо с вложением M.store(num, '+FLAGS', '\\Deleted') ...
Офлайн
0
pyuserНаверно здесь обрабатываем письмо без вложения.
Нужно слегка изменить логику:
#Check if any attachments at all
if mail.get_content_maintype() == ‘multipart’:
# здесь обрабатываем письмо с вложением
M.store(num, ‘+FLAGS’, ‘\\Deleted’)
…
#!/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 != ['']: if not os.path.isdir(detach_new): <----------------- 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': M.store(num, '+FLAGS', '\\Deleted') <----------------- 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()
Отредактировано kolin_k (Апрель 1, 2014 08:52:06)
Офлайн
36
kolin_kДля писем без вложений:
Наверно здесь обрабатываем письмо без вложения.
mail.get_content_maintype() != 'multipart'
Офлайн
0
За ночь пришла в голову идея дату брать из письма, а не текущую. Тогда будет более универсально. Не знаете как?
Нашел такую команду:
print mail['Date']
Tue, 01 Apr 2014 10:35:11 +0400
day = mail['Date'] newday = day[5:16] print(newday)
01 Apr 2014
Отредактировано kolin_k (Апрель 1, 2014 10:08:07)
Офлайн
36
kolin_kУстановите пакет dateutil
Как можно перевести в формат гггг-мм-дд ?
>>> from dateutil import parser
>>> parser.parse("Tue, 01 Apr 2014 10:35:11 +0400")
datetime.datetime(2014, 4, 1, 10, 35, 11, tzinfo=tzoffset(None, 14400))
Офлайн
0
dateutil установил.
from dateutil import parser ... day = mail['Date'] newday = dateutil.parser.parse(day)
Traceback (most recent call last): File "./imap_detach_folder.py", line 39, in <module> newday = dateutil.parser.parse(day) NameError: name 'dateutil' is not defined
day = mail['Date'] newday = parser.parse(day).date() print(newday)
Отредактировано kolin_k (Апрель 1, 2014 11:56:19)
Офлайн
0
Вроде все получилось. Остался один косяк, но это уже наверно не сюда. Хотя если будут мысли, с радостью прочитаю.
Косяк. Если выкладывать аттачи в одну кучу, без создании папки, то они спокойно удаляются с шары из винды, согласно выданным правам.
А вот если, как сейчас раскидывать по папкам, то файлы не удалить. Верней вроде удалил, а обновил папку, файлы снова там. Вобщем пока думаю, почему так.
Итог скрипта такой:
#!/usr/bin/env python import getpass, imaplib, email, os, datetime from email import parser from dateutil import parser M = imaplib.IMAP4('mail.ru') M.login('test@mail.ru', 'password') M.select() typ, data = M.search(None, 'ALL') 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': M.store(num, '+FLAGS', '\\Deleted') continue # 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': day = str(parser.parse(mail['Date']).date()) detach_dir = '/home/samba/shares/unique/' + day + '/' if not os.path.isdir(detach_dir): os.makedirs(detach_dir) 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.store(num, '+FLAGS', '\\Deleted') M.close() M.logout()
Офлайн
0
pyuser
Может знаете, как выкладывать файл на виндовую шару в этом скрипте?
Офлайн
36
kolin_kВам уже пора научиться help'ом пользоваться, у объектов datetime есть метод strftimeday = str(parser.parse(mail['Date']).date())
kolin_kЯ в windows работаю, для меня сохранение в расшаренную папку ни чем не отличается от сохранения в локальную.
Может знаете, как выкладывать файл на виндовую шару в этом скрипте?
Офлайн