使用 Python 標準庫 imaplib 透過 IMAP over SSL (埠口 993) 連接 Gmail,搜尋、讀取、解析郵件內容 (含多部分 MIME、附件)。
import imaplib
IMAP_HOST = 'imap.gmail.com'
IMAP_PORT = 993
USER = 'your@gmail.com'
PASS = 'your_app_password'
with imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT) as mail:
mail.login(USER, PASS)
status, mailboxes = mail.list()
print('Mailboxes:', mailboxes)
# [('(\\HasNoChildren)', '.', 'INBOX'), ('(\\HasNoChildren)', '.', '[Gmail]/Sent Mail'), ...]
with imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT) as mail:
mail.login(USER, PASS)
mail.select('INBOX') # 唯讀用 select(readonly=True)
# 搜尋條件:ALL, UNSEEN, FROM "xxx", SUBJECT "xxx", SINCE "01-Jan-2024"
status, data = mail.search(None, 'UNSEEN') # 未讀郵件
mail_ids = data[0].split()
print(f"Unseen count: {len(mail_ids)}")
# 取得最新 5 封
for num in mail_ids[-5:]:
status, msg_data = mail.fetch(num, '(RFC822)')
raw_email = msg_data[0][1]
# 解析見下文
import email
from email.header import decode_header
def parse_email(raw_bytes):
msg = email.message_from_bytes(raw_bytes)
# 解碼主旨
subject, encoding = decode_header(msg['Subject'])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or 'utf-8')
# 發件人
from_raw = msg.get('From')
from_decoded = decode_header(from_raw)[0][0]
if isinstance(from_decoded, bytes):
from_decoded = from_decoded.decode(encoding or 'utf-8')
print(f"Subject: {subject}")
print(f"From: {from_decoded}")
print(f"Date: {msg.get('Date')}")
# 處理多部分訊息
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
disp = str(part.get('Content-Disposition', ''))
# 文字內容
if ctype == 'text/plain' and 'attachment' not in disp:
body = part.get_payload(decode=True)
charset = part.get_content_charset() or 'utf-8'
print(f"Text Body:\n{body.decode(charset, errors='replace')[:500]}...")
# HTML 內容
elif ctype == 'text/html' and 'attachment' not in disp:
html = part.get_payload(decode=True)
charset = part.get_content_charset() or 'utf-8'
# 可另存為 .html 檔案
# 附件
elif 'attachment' in disp:
filename = part.get_filename()
if filename:
filename = decode_header(filename)[0][0]
if isinstance(filename, bytes):
filename = filename.decode(encoding or 'utf-8')
print(f"Attachment: {filename}")
# 儲存附件
# with open(filename, 'wb') as f: f.write(part.get_payload(decode=True))
else:
# 非多部分
body = msg.get_payload(decode=True)
charset = msg.get_content_charset() or 'utf-8'
print(f"Body:\n{body.decode(charset, errors='replace')[:500]}...")
| 準則 | 說明 |
|---|---|
ALL | 所有郵件 |
UNSEEN | 未讀 |
SEEN | 已讀 |
FROM "addr" | 寄件者 |
TO "addr" | 收件者 |
SUBJECT "keyword" | 主旨包含關鍵字 |
BODY "keyword" | 內文包含關鍵字 |
SINCE "DD-Mon-YYYY" | 日期之後 |
BEFORE "DD-Mon-YYYY" | 日期之前 |
LARGER size | 大於 size bytes |
SMALLER size | 小於 size bytes |
可組合:mail.search(None, 'FROM "boss@company.com" UNSEEN SINCE "01-Jan-2024"')
pip install imapclient
from imapclient import IMAPClient
with IMAPClient('imap.gmail.com', ssl=True) as client:
client.login(USER, PASS)
client.select_folder('INBOX')
messages = client.search(['UNSEEN'])
for uid, data in client.fetch(messages, ['RFC822']).items():
# data[b'RFC822'] 為原始郵件
pass
imapclient API 更 Pythonic、支援 UID、自動處理編碼、回傳字典結構。