Created
March 1, 2018 09:20
-
-
Save billiepander/3b5c8e9c9b5a01dd838cd1da1c48a97e to your computer and use it in GitHub Desktop.
python3 to download certain unread email's attatchment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import email | |
| import imaplib | |
| import os | |
| from email.header import decode_header | |
| detach_dir = '.' | |
| if 'attachments' not in os.listdir(detach_dir): | |
| os.mkdir('attachments') | |
| import os | |
| already_fielnames = os.listdir("attachments") | |
| userName = 'xxxx@??.yyy' | |
| passwd = 'password' | |
| try: | |
| imapSession = imaplib.IMAP4('imap.qq.com') | |
| typ, accountDetails = imapSession.login(userName, passwd) | |
| if typ != 'OK': | |
| print('Not able to sign in!') | |
| raise | |
| imapSession.select('inbox') | |
| typ, data = imapSession.search(None, '(UNSEEN)') | |
| if typ != 'OK': | |
| print('Error searching Inbox.') | |
| raise | |
| ids = data[0].split() | |
| ids.reverse() | |
| for msgId in ids: | |
| from email.parser import HeaderParser | |
| data = imapSession.fetch(msgId, '(BODY[HEADER.FIELDS (SUBJECT FROM)])') | |
| header_data = data[1][0][1] | |
| header_data = email.message_from_bytes(header_data) | |
| header_data = dict(header_data._headers) | |
| fileName, _ = decode_header(header_data.get('Subject', ''))[0] | |
| if isinstance(fileName, bytes): | |
| fileName = fileName.decode() | |
| header_data['Subject'] = fileName | |
| if 'xxxx' not in header_data['From'] or 'xxxx' not in header_data['Subject']: | |
| break | |
| typ, messageParts = imapSession.fetch(msgId, '(RFC822)') | |
| if typ != 'OK': | |
| raise | |
| emailBody = messageParts[0][1] | |
| mail = email.message_from_bytes(emailBody) | |
| for part in mail.walk(): | |
| if part.get_content_maintype() == 'multipart': | |
| continue | |
| if part.get('Content-Disposition') is None: | |
| continue | |
| fileName = part.get_filename() | |
| fileName, _ = decode_header(fileName)[0] | |
| if isinstance(fileName, bytes): | |
| fileName = fileName.decode() | |
| if fileName in already_fielnames: | |
| break | |
| if bool(fileName): | |
| filePath = os.path.join(detach_dir, 'attachments', fileName) | |
| if not os.path.isfile(filePath): | |
| fp = open(filePath, 'wb') | |
| fp.write(part.get_payload(decode=True)) | |
| fp.close() | |
| imapSession.close() | |
| imapSession.logout() | |
| except Exception as e: | |
| raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment