개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.06.26 10:40

imap_savebody 함수 사용에 대한 질문

목록
  • 모바일최적화광 12시간 전 2025.06.26 10:40 새글
  • 4
    1
선생님, imap_savebody 함수를 사용하여 메일을 저장할 때, attachments 파일을 어떻게 지정해야 하는지 알려주세요.

내가 현재 사용 중인 코드는 다음과 같습니다:

python

import imaplib

import email



# imaplib를 사용하여 메일을 연결합니다

mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login('내 이메일 주소', '비밀번호')

mail.select('inbox')



# 메일을 검색합니다

status, messages = mail.search(None, 'ALL')



# 메시지를 읽습니다

for num in messages[0].split():

    status, msg = mail.fetch(num, '(RFC822)')

    raw_message = msg[0][1]

    

    # 메일을 파서로 분리합니다

    email_message = email.message_from_bytes(raw_message)

    

    # 메일의 본문을 저장합니다

    with open(f'mail_{num}.txt', 'wb') as f:

        f.write(email_message.get_payload(decode=True))

    

    # 첨부파일을 저장합니다

    if email_message.get_content_maintype() == 'multipart':

        for part in email_message.walk():

            if part.get_content_maintype() == 'application':

                filename = part.get_filename()

                if filename:

                    with open(f'attachments/{filename}', 'wb') as f:

                        f.write(part.get_payload(decode=True))



imap_savebody 함수를 사용하여 첨부파일을 저장할 때, attachments 폴더에 저장되는 파일 이름이 원본의 첨부파일 이름과 다르게 저장되는 문제가 있습니다.

원본 첨부파일 이름과 같이 첨부파일을 저장하려면 어떻게 해야 하는지 알려주세요.

    댓글목록

    profile_image
    나우호스팅  12시간 전



    imap_savebody 함수를 사용하여 첨부파일을 저장할 때 원본 첨부파일 이름을 유지하려면, 첨부파일을 저장할 때 filename 변수를 사용하여 파일 이름을 지정하는 대신 part.get_filename() 함수를 사용하여 원본 파일 이름을 직접 지정할 수 있습니다.

    다음과 같이 코드를 수정하여 첨부파일을 저장할 때 원본 첨부파일 이름을 유지할 수 있습니다.

    #hostingforum.kr
    python
    
    # 첨부파일을 저장합니다
    
    if email_message.get_content_maintype() == 'multipart':
    
        for part in email_message.walk():
    
            if part.get_content_maintype() == 'application':
    
                filename = part.get_filename()
    
                if filename:
    
                    # 원본 첨부파일 이름을 유지하기 위해 filename 변수를 사용하지 말고 part.get_filename() 함수를 사용합니다.
    
                    with open(f'attachments/{filename}', 'wb') as f:
    
                        f.write(part.get_payload(decode=True))
    
    


    이러한 수정을 통해 첨부파일을 저장할 때 원본 첨부파일 이름을 유지할 수 있습니다.

    2025-06-26 10:41

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 31,091건 / 5 페이지

검색

게시물 검색