지메일(Gmail) 대량 세금계산서·첨부파일 1초 만에 날짜별 자동 다운로드 및 정리 (파이썬)

📬 "월말마다 받은 편지함 열어두고 첨부파일 '저장' 버튼 수십 번 누르다 지치셨나요?"

거래처에서 보낸 세금계산서, 정산서, 보고서 PDF... 파이썬 내장 라이브러리인 imaplib과 email 모듈을 활용하면 클릭 한 번에 '오늘 받은 메일'의 첨부파일만 날짜별 폴더로 자동 다운로드하고 정리할 수 있습니다.

1. 지메일 IMAP 파이프라인 구조

보안을 위해 계정 기본 비밀번호 대신 구글 계정 설정의 [앱 비밀번호(App Password)]를 발급받아 스크립트에 등록하면, 브라우저를 띄우지 않고도 백그라운드에서 안전하게 메일함에 접근할 수 있습니다.


2. 20줄 핵심 파이썬 스크립트

import imaplib
import email
from email.header import decode_header
import os

def download_attachments(user_email, app_password, search_subject="세금계산서"):
    os.makedirs("downloads", exist_ok=True)
    mail = imaplib.IMAP4_SSL("imap.gmail.com")
    mail.login(user_email, app_password)
    mail.select("inbox")
    
    # 제목 키워드로 검색
    status, messages = mail.search(None, f'(SUBJECT "{search_subject}")')
    mail_ids = messages[0].split()
    
    for m_id in mail_ids[-10:]: # 최근 10건 처리
        _, msg_data = mail.fetch(m_id, "(RFC822)")
        msg = email.message_from_bytes(msg_data[0][1])
        
        for part in msg.walk():
            if part.get_content_maintype() == "multipart" or not part.get("Content-Disposition"):
                continue
            filename = part.get_filename()
            if filename:
                decoded_fn, enc = decode_header(filename)[0]
                if isinstance(decoded_fn, bytes):
                    decoded_fn = decoded_fn.decode(enc or "utf-8")
                save_path = os.path.join("downloads", decoded_fn)
                with open(save_path, "wb") as f:
                    f.write(part.get_payload(decode=True))
                print(f"📥 저장 완료: {decoded_fn}")
    mail.logout()

# download_attachments("my_account@gmail.com", "앱_비밀번호_16자리")

3. 스케줄러 연동으로 완전 자동 백업 완성

이 코드를 로컬 스케줄러나 클라우드 서버에 등록해 두면, 매일 퇴근 전 당일 인입된 모든 중요 영수증 파일이 로컬 드라이브에 안전하게 자동 아카이빙됩니다.


🛠️ 설치 없이 바로 쓰는 무료 실무 웹도구 (DailyTools)

복잡한 설치나 코딩 없이 브라우저에서 즉시 실행 가능한 무료 생산성 웹 유틸리티 허브를 지금 바로 이용해 보세요.

다음 이전