파이썬 - Gmail 모든 첨부파일 내려받기

정태경·2022년 1월 15일
0

퇴사할 때 유용하게 사용했던 코드

#-*- coding: utf-8 -*-
import email
import imaplib
import os
import time
import re
import base64
import quopri

def encoded_words_to_text(encoded_words):
    try:
        encoded_word_regex = r'=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}='
        charset, encoding, encoded_text = re.match(encoded_word_regex, encoded_words).groups()
        if encoding is 'B':
            byte_string = base64.b64decode(encoded_text)
        elif encoding is 'Q':
            byte_string = quopri.decodestring(encoded_text)
        return byte_string.decode(charset)
    except:
        return encoded_words

detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
    os.mkdir('attachments')

userName = 'abc@abc.com' # 메일 계정
passwd = 'password' # 메일 비번

try:
    imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)
    typ, accountDetails = imapSession.login(userName, passwd)

    print(imapSession.list())

    for i in imapSession.list()[1]:
        l = i.decode().split(' "/" ')
        print(l[0] + " = " + l[1])

    if typ != 'OK':
        print ('로그인 불가')
        raise

    imapSession.select('6_TKJUNG/ETC')                      # 사서함 이름
    typ, data = imapSession.search(None, 'ALL')
    if typ != 'OK':
        print ('인박스 검색 중 에러 발생')
        raise

    # 모든 메일에 대해 반복 실행
    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')

        if typ != 'OK':
            print ('메일 가져오는 중 에러 발생')
            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 = encoded_words_to_text(fileName)

            if bool(fileName):
                filePath = os.path.join(detach_dir, 'attachments', fileName)
                if not os.path.isfile(filePath) :
                    print(fileName)
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()

    imapSession.close()
    imapSession.logout()

except :
    print ('첨부 파일 다운로드 불가')
    time.sleep(3)
profile
現 두나무 업비트 QA 엔지니어, 前 마이리얼트립 TQA 엔지니어

0개의 댓글