Notice
Recent Posts
Recent Comments
Link
«   2026/05   »
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 29 30
31
Archives
Today
Total
관리 메뉴

yyangman의 개발일지

Python으로 오늘 받은 메일 가져오기 본문

django

Python으로 오늘 받은 메일 가져오기

yyangman 2023. 1. 30. 13:50

먼저, imap, email 라이브러리를 통해 imap 로그인을 한다

 

import imaplib
import email


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

imap.login('사용자 이메일', '16자리 비밀번호') #16자리 비밀번호는 구글 2차 인증하여 생긴 비밀번호

 

 

 

uid 메서드를 통해 이메일을 끌어온다. split()은 가져온 이메일 바이너리 코드를 정리해주는 메서드이다

 

imap.select("INBOX")

status, messages = imap.uid('search', None, 'ALL')

messages = messages[0].split() # 이때 messages의 타입은 list

 

 

fetch() 명령어를 통해 이메일을 가져온다. 이때 messages[-1]은 가장 최근 받은 이메일을 의미한다. messages[-2]이면 가장 최근 두번째 이메일을 의미한다. 가장 오래된 메일을 messages[0]에 해당한다

 

r_email = messages[-1]

# fetch 명령어
res, msg = imap.uid('fetch', r_email, "(RFC822)")
# 사람이 읽을 수 있는 형태로 변환
raw = msg[0][1].decode('utf-8')

 

 

 

현재 날짜와 메일의 날짜 비교하기

1. 현재 시간을 제공하는 메서드 datetime은 통해 현재 날짜를 d에다가 넣는다

2. 이메일의 날짜를 받아와서 date에다가 넣는다. 이때 date는 튜플 타입이기에 date[0]에 이메일의 날짜가 저장되어 있다

3. 문자열을 날짜로 형변환해주는 strptime메서드를 통해 temp에다가 날짜 타입 date를 선언한다

4. 이렇게되면 d에는 현재 날짜, temp에는 메일의 날짜가 저장된다

 

email_message = email.message_from_string(raw)
d = datetime.now().day
date = decode_header(email_message.get("Date"))[0]
temp = datetime.strptime(date[0], '%a, %d %b %Y %H:%M:%S %z')

if d != temp.day:
	   break
i = -1
while d == temp.day:
	...
	...

 

 

 

반복문을 통해 True 인 메일만 출력하기

1. d와 temp.day가 같으면 반복문이 실행되고 그렇지 않으면 반복문이 종료됨

2. email 라이브러리를 통해 보낸사람, 메일제목, 메일시간, 메일내용을 파싱하여 출력한다

3. 반복문 끝에 i = i - 1을 하여 그 다음 메일이 나오도록 한다

 

while d == temp.day:
    r_email = messages[i]
    # fetch 명령어로 메일 가져오기
    res, msg = imap.uid('fetch', r_email, "(RFC822)")
    # 사람이 읽을 수 있는 형태로 변환
    raw = msg[0][1].decode('utf-8')
    # raw_readable에서 원하는 부분만 파싱하기 위해 email 모듈을 이용해 변환
    email_message = email.message_from_string(raw)

    # 보낸사람
    fr = make_header(decode_header(email_message.get('From')))
    print(fr)

    # 메일 제목
    subject = make_header(decode_header(email_message.get('Subject')))
    print(subject)

    #메일 시간
    date = decode_header(email_message.get("Date"))[0]
    temp = datetime.strptime(date[0], '%a, %d %b %Y %H:%M:%S %z')
    #print(temp.day)

    # 메일 내용
    if email_message.is_multipart():
        for part in email_message.walk():
            ctype = part.get_content_type()
            cdispo = str(part.get('Content-Disposition'))
            if ctype == 'text/plain' and 'attachment' not in cdispo:
                body = part.get_payload(decode=True)  # decode
                break
            
    else:
        body = email_message.get_payload(decode=True)

    body = body.decode('utf-8')
    print(body)
    i-=1

 

'django' 카테고리의 다른 글

django 와 Postgresql 연동  (0) 2023.01.26