개발자 Q&A

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

2025.04.13 08:53

imap_fetchmime 메시지 내용을 읽는 방법에 대한 질문입니다.

목록
  • 해킹방어수호자 2일 전 2025.04.13 08:53
  • 39
    1
내용:

안녕하세요, 선생님.

imap_fetchmime 메시지 내용을 읽는 방법에 대해 질문하고 싶습니다.
imap_fetchmime 메시지를 사용하여 메시지 내용을 읽으려고 하는데,
내가 사용하는 코드는 다음과 같습니다.

python

import imaplib

import email



# imap 서버와 연결

mail = imaplib.IMAP4('imap.example.com')

mail.login('username@example.com', 'password')

mail.select('inbox')



# 메시지 검색

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



# 메시지 읽기

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

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

    for part in msg:

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

            print(part.get_payload(decode=True).decode())



이 코드는 메시지 내용을 읽는 데 성공했는데,
일부 메시지에서 메시지 내용을 읽지 못하고 있습니다.
이 경우에는 어떻게 해야 하는지 알려주시겠습니까?

감사합니다.

    댓글목록

    profile_image
    나우호스팅  2일 전



    imap_fetchmime 메시지 내용을 읽는 방법에 대해 설명드리겠습니다.

    imap_fetchmime 메시지를 사용하여 메시지 내용을 읽으려면, 메시지의 MIME 타입을 확인하고, 해당 타입의 내용을 읽어야 합니다.

    이 경우, 메시지 내용을 읽지 못하는 경우는 메시지의 MIME 타입이 text/html 인 경우입니다.

    이 경우, 메시지 내용을 읽으려면, HTML 파서를 사용하여 HTML 내용을 텍스트로 변환해야 합니다.

    Python의 경우, BeautifulSoup 라이브러리를 사용하여 HTML 파서를 만들 수 있습니다.

    다음은 메시지 내용을 읽는 방법을示한 예제입니다.

    #hostingforum.kr
    python
    
    import imaplib
    
    import email
    
    from bs4 import BeautifulSoup
    
    
    
    # imap 서버와 연결
    
    mail = imaplib.IMAP4('imap.example.com')
    
    mail.login('username@example.com', 'password')
    
    mail.select('inbox')
    
    
    
    # 메시지 검색
    
    status, messages = mail.search(None, 'UNSEEN')
    
    
    
    # 메시지 읽기
    
    for num in messages[0].split():
    
        status, msg = mail.fetch(num, '(RFC822)')
    
        for part in msg:
    
            if part.get_content_maintype() == 'text':
    
                print(part.get_payload(decode=True).decode())
    
            elif part.get_content_maintype() == 'html':
    
                soup = BeautifulSoup(part.get_payload(decode=True).decode(), 'html.parser')
    
                print(soup.get_text())
    
    


    이 예제는 메시지 내용을 읽는 데 성공했을 때, 메시지 내용을 읽지 못하는 경우를 처리하여 메시지 내용을 읽는 데 도움이 됩니다.

    2025-04-13 08:54

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

검색

게시물 검색