티스토리 뷰

만든거

자동파일 다운로드

tl;dr 2024. 7. 23. 14:41

import imaplib
import email
import os
import re
from email.header import decode_header, make_header

# 네이버 웍스 IMAP 서버 설정
IMAP_SERVER = '
IMAP_PORT = 
EMAIL_ACCOUNT =
PASSWORD = 'your_app_password'  # 외부 앱 비밀번호를 여기에 입력하세요

# 저장할 디렉토리 설정
SAVE_DIR = './downloads'
if not os.path.exists(SAVE_DIR):
    os.makedirs(SAVE_DIR)

# 파일 이름을 유효한 형식으로 변환하는 함수
def clean_filename(filename):
    filename = str(make_header(decode_header(filename)))
    filename = re.sub(r'[\\/*?:"<>|]', "", filename)
    return filename

# 메일함에서 메일 읽기 및 첨부파일 저장 함수
def download_attachments():
    try:
        mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
        mail.login(EMAIL_ACCOUNT, PASSWORD)
        mail.select('inbox')

        # 안 읽은 메일 검색
        status, data = mail.search(None, 'UNSEEN')
        mail_ids = data[0].split()

        for mail_id in mail_ids:
            status, msg_data = mail.fetch(mail_id, '(RFC822)')
            raw_email = msg_data[0][1]
            msg = email.message_from_bytes(raw_email)

            if msg.get_content_maintype() != 'multipart':
                continue

            for part in msg.walk():
                if part.get_content_maintype() == 'multipart':
                    continue
                if part.get('Content-Disposition') is None:
                    continue

                filename = part.get_filename()
                if filename:
                    filename = clean_filename(filename)
                    filepath = os.path.join(SAVE_DIR, filename)
                    with open(filepath, 'wb') as f:
                        f.write(part.get_payload(decode=True))
                    print(f'Downloaded: {filename}')

        mail.logout()
    except imaplib.IMAP4.error as e:
        print(f'IMAP error: {e}')
    except Exception as e:
        print(f'Error: {e}')

if __name__ == '__main__':
    download_attachments()

 

GPT돌려서 대충 만들었는데 대강 돌아가는 방법만 알고 디테일은 다음에 알아가야겠다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함