파이썬으로 Outlook 메일 모니터링 프로그램 만들기
메일 모니터링, 왜 필요했을까?
업무용 소형 디스플레이를 하나 구매했습니다. 모니터링 기능으로 띄워놓을 게 뭐 없나 고민하던 차, Outlook이 떠오르더군요. 업무 중 중요한 이메일을 놓치지 않으려면 메일함을 자주 확인해야 하는데, 매번 Outlook을 열어 확인하는 게 생각보다 번거롭더라고요. 그래서 읽지 않은 메일 개수를 실시간으로 확인하고, 최신 메일 몇 개를 한눈에 볼 수 있는 간단한 프로그램을 만들어보기로 했습니다. 파이썬으로 구현한 이 프로그램은 초보자도 따라 하기 쉬운 코드로 구성되어 있으니, 여러분도 한번 도전해보세요!
프로그램의 주요 기능
제가 만들고자 했던 프로그램의 주요 기능은 다음과 같습니다:
- 읽지 않은 메일 개수 표시: 현재 읽지 않은 메일 수를 실시간으로 보여줍니다.
- 최신 메일 15개 표시: 발신자, 제목, 수신 시간을 테이블 형식으로 정리합니다.
- 읽지 않은 메일 강조: 읽지 않은 메일은 배경색으로 시각적으로 구분합니다.
- 자동 갱신: 데이터를 일정 간격(10초)마다 자동으로 갱신합니다.
구현 과정
1. Outlook 데이터 가져오기
Outlook 데이터를 가져오기 위해 Windows 환경에서 동작하는 pywin32
라이브러리를 사용했습니다. 이 라이브러리를 통해 Outlook과 상호작용할 수 있습니다.
pip install pywin32
설치 후 받은 편지함 데이터를 가져오는 코드는 다음과 같습니다:
import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # 받은 편지함 messages = inbox.Items messages.Sort("[ReceivedTime]", True) # 최신순 정렬
2. GUI 구성
데이터를 보기 좋게 표시하기 위해 파이썬의 기본 GUI 라이브러리인 tkinter
를 사용했습니다. 읽지 않은 메일 개수는 라벨로 표시하고, 최신 메일 리스트는 ttk.Treeview
를 사용해 테이블 형식으로 구성했습니다.
3. 읽지 않은 메일 강조
읽지 않은 메일은 테이블에서 옅은 파란색 배경으로 강조되도록 설정했습니다. 이를 위해 Treeview의 태그 기능을 활용했습니다.
tree.tag_configure("unread", background="#D9EDF7") # 옅은 파란색 tree.tag_configure("read", background="white") # 기본 흰색
4. 자동 갱신
데이터를 일정 간격마다 갱신하기 위해 tkinter
의 after()
메서드를 사용했습니다. 이 코드를 통해 프로그램이 매 10초마다 데이터를 업데이트하도록 설정했습니다.
root.after(10000, update_gui) # 10초마다 갱신
완성된 코드
아래는 최종 완성된 코드입니다. 이 코드는 읽지 않은 메일 개수와 최신 메일 리스트를 실시간으로 보여줍니다.
import win32com.client
import tkinter as tk
from tkinter import ttk
from datetime import datetime
def read_outlook_emails():
"""
Outlook에서 메일 데이터를 읽어옴.
읽지 않은 메일의 카운트를 계산하고, 최근 15개의 메일을 반환.
"""
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # 6은 Inbox 폴더를 의미
messages = inbox.Items
messages.Sort("[ReceivedTime]", True) # 수신 시간 기준으로 내림차순 정렬
unread_count = 0
email_data = []
for message in messages:
try:
# 읽지 않은 메일 카운트 증가
if message.UnRead:
unread_count += 1
# 최근 15개의 메일만 저장
if len(email_data) < 15:
email_data.append({
"Sender": message.SenderName,
"Subject": message.Subject,
"ReceivedTime": message.ReceivedTime.strftime("%y-%m-%d %H:%M"), # 초 제거
"Read": "Read" if not message.UnRead else "Unread"
})
except Exception as e:
print(f"Error reading email: {e}")
return unread_count, email_data
def update_gui():
"""
GUI를 업데이트하며 읽지 않은 메일 카운트와 최근 15개 메일을 표시.
"""
unread_count, email_data = read_outlook_emails()
# 현재 시간 가져오기 (업데이트 일시)
current_time = datetime.now().strftime("%y-%m-%d %H:%M") # 초 제거
# 읽지 않은 메일 카운트 및 업데이트 일시 표시
unread_label.config(text=f"Unread Emails: {unread_count} (Last Update: {current_time})")
# 테이블 초기화
for row in tree.get_children():
tree.delete(row)
# 새 데이터 삽입 (최근 15개)
for email in email_data:
tag = "unread" if email["Read"] == "Unread" else "read"
tree.insert("", "end", values=(email["Sender"], email["Subject"], email["ReceivedTime"], email["Read"]), tags=(tag,))
# 10초 후 다시 실행
root.after(10000, update_gui)
# tkinter 윈도우 생성
root = tk.Tk()
root.title("Outlook Email Monitor")
root.geometry("800x400")
# 기본 폰트 설정 (Noto Sans KR, 9포인트)
default_font = ("Noto Sans KR", 9)
# 읽지 않은 메일 카운트를 표시할 라벨 생성
unread_label = tk.Label(root, text="Unread Emails: 0", font=default_font)
unread_label.pack(pady=10)
# 테이블 생성
columns = ("Sender", "Subject", "ReceivedTime", "Read")
tree = ttk.Treeview(root, columns=columns, show="headings")
tree.heading("Sender", text="Sender")
tree.heading("Subject", text="Subject")
tree.heading("ReceivedTime", text="Received Time")
tree.heading("Read", text="Read/Unread")
# 테이블 폰트 설정 (Noto Sans KR, 9포인트)
style = ttk.Style()
style.configure("Treeview.Heading", font=default_font) # 헤더 폰트
style.configure("Treeview", font=default_font) # 테이블 내용 폰트
# Treeview 색상 태그 설정 (Unread 항목에 옅은 파란색 배경 추가)
tree.tag_configure("unread", background="#D9EDF7") # 옅은 파란색 (#D9EDF7)
tree.tag_configure("read", background="white") # 기본 흰색
tree.pack(fill=tk.BOTH, expand=True)
# 초기 업데이트 호출
update_gui()
# GUI 루프 실행
root.mainloop()
결론적으로...
이번 프로젝트를 통해 파이썬으로 Windows 환경에서 Outlook 데이터를 다루고 간단한 GUI 프로그램을 만드는 방법을 배울 수 있었습니다. 초보자도 쉽게 따라 할 수 있는 내용이니 여러분도 도전해보세요! 궁금한 점이나 개선 아이디어가 있다면 댓글로 남겨주세요!