1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import os
import sys
import imaplib
import email
detach_dir = './mail/'
if 'mail' not in os.listdir('.'):
os.mkdir('mail')
userName = "xxxxxxx@gmail.com"#mail
passwd = "******"#mdp mail
def get_body(msg):
if msg.is_multipart():
return get_body(msg.get_payload(0))
else:
return msg.get_payload(None,True)
def get_attachments(msg):
l=[]
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
l=[part.get_payload(decode=True),part.get_filename()]
return l
M = imaplib.IMAP4_SSL('imap.gmail.com')
typ, accountDetails = M.login(userName, passwd)
M.select()
typ, data = M.search(None, 'ALL')
i=0
for msgId in data[0].split():
typ, messageParts = M.fetch(msgId, '(RFC822)')
raw = email.message_from_bytes(messageParts[0][1])
fileName = raw['subject']
datee=raw['Date']
dateee=datee[0:3]+datee[5:7]+ datee[8:11]+datee[14:16]
dosname=dateee+raw['subject']
filePath = os.path.join(detach_dir, fileName)
os.chdir('/C:Users/admin/Downloads')
if not os.path.isfile(filePath) :
fp = open(filePath, 'wb')
fp.write(get_body(raw))
fp.close()
try:
L=get_attachments(raw)
except:
L=[]
if type(L)!= list :
L=[]
if len(L)!= 0 :
fileName=L[1]
filePath = os.path.join(detach_dir,fileName)
os.chdir('chemin')
if not os.path.isfile(filePath) :
fp = open(filePath, 'wb')
fp.write(L[0])
fp.close()
M.close()
M.logout()
print("done") |
Partager