Python을 활용한 이메일 자동화

1. 필요한 모듈 설치 ---------

pip install yagmail  # Gmail뿐만 아니라 다른 메일 서비스에서도 사용 가능한 간단한 메일 송신 모듈
pip install keyring  # 암호를 안전하게 관리하여 코드에 민감한 정보를 하드코딩하지 않도록 함
pip install schedule # 주기적인 작업 스케줄링
pip install mbox     # 메일 처리를 위한 도구 제공
2. 기본 사용법 ------ ### 1) 암호 저장 및 불러오기

import keyring
import yagmail

yagmail.register('example@gmail.com', 'securepassword')  # 한 번 등록하면 이후에는 암호 입력이 필요 없음 (암호 변경 시 재등록 가능)
password = keyring.get_password("yagmail", "example@gmail.com")  # 암호 가져오기
print(password)
### 2) 이메일 보내기

import yagmail

# SMTP 설정 (이미 등록된 계정은 암호 생략 가능)
yag = yagmail.SMTP(user='example@gmail.com', host='smtp.gmail.com', port=587)

# 본문 내용 작성 (텍스트, HTML, 첨부 파일 포함 가능)
content = [
    "안녕하세요! 이는 테스트 메일입니다.",
    "<a href="https://www.google.com">Google 검색</a>",
    "sample.jpg",
    yagmail.inline("sample.jpg")  # 첨부 파일을 본문 내에서 표시하기
]

# 이메일 발송 (수신자 여러 명인 경우 리스트로 전달 가능)
yag.send(to='recipient@example.com', subject='테스트 이메일', contents=content)
### 3) 주기적인 이메일 발송

import schedule
import time

def send_email():
    print("이메일 발송 중...")

# 스케줄 예약
schedule.every(10).minutes.do(send_email)  # 매 10분마다 실행
schedule.every().hour.do(send_email)       # 매 시간마다 실행
schedule.every().day.at("14:00").do(send_email)  # 매일 오후 2시에 실행

while True:
    schedule.run_pending()
    time.sleep(1)
### 4) 수신 및 이메일 검색

import keyring
from imbox import Imbox

password = keyring.get_password("yagmail", "example@gmail.com")
with Imbox('imap.gmail.com', username='example@gmail.com', password=password, ssl=True) as inbox:
    messages = inbox.messages(unread=True)  # 읽지 않은 메일만 가져오기
    
    for uid, message in messages:
        print(f"UID: {uid}")
        print(f"제목: {message.subject}")
        print(f"본문: {message.body['plain'][0]}")  # 텍스트 형식 본문 출력

# 추가적인 필터 옵션
# sent_from="特定발신자" - 특정 발신자의 메일 필터링
# date__gt=datetime.date(2023, 1, 1) - 특정 날짜 이후의 메일 필터링
# flagged=True - 중요 표시된 메일 필터링

태그: python yagmail keyring schedule imbox

7월 28일 16:56에 게시됨