I'm trying to extract files from emails via IMAP using Python 3.7 (on Windows, fyi) and each of my attempts shows extracted files with Modification & Creation Date = time of extraction (which is incorrect).
As full email applications have the ability to preserve that information, it must me stored somewhere. I also gave working with structs a try, thinking the information may be stored in binary, but had no luck.
import emailfrom email.header import decode_headerimport imaplibimport osSERVER = NoneOUT_DIR = '/var/out'IMP_SRV = 'mail.domain.tld'IMP_USR = 'user@domain.tld'IMP_PWD = 'hunter2'def login_mail(): global SERVER SERVER = imaplib.IMAP4_SSL(IMP_SRV) SERVER.login(IMP_USR, IMP_PWD)def get_mail(folder='INBOX'): mails = [] _, data = SERVER.uid('SEARCH', 'ALL') uids = data[0].split() for uid in uids: _, s = SERVER.uid('FETCH', uid, '(RFC822)') mail = email.message_from_bytes(s[0][1]) mails.append(mail) return mailsdef parse_attachments(mail): for part in mail.walk(): if part.get_content_type() == 'application/octet-stream': filename = get_filename(part) output = os.path.join(OUT_DIR, filename) with open(output, 'wb') as f: f.write(part.get_payload(decode=True))def get_filename(part): filename = part.get_filename() binary = part.get_payload(decode=True) if decode_header(filename)[0][1] is not None: filename = decode_header(filename)[0][0].decode(decode_header(filename)[0][1]) filename = os.path.basename(filename) return filename
Can anyone tell me what I'm doing wrong and if it's somehow possible?
After getting said information it could be possible to modify the timestamps utilizing How do I change the file creation date of a Windows file?.