ネット上にコード例が多々ありますが、古い出典は動かない場合があります。
AIの回答が一番簡単に動作しました。
以下、サンプルコード
#------------------------------------------------------------------------------------------
#ねらい:Thunderbirdの受信メールフォルダからメール文を得る
#前提1:既存のgmailアカウントでThunderbirdにてPOP受信できている
#前提2:gmailアカウントの受信メールボックス(Inbox)にフォルダを設けてある。
(例:mail4python)
#標準ライブラリ
import mailbox
from email.header import decode_header
#Thunderbirdのメールフォルダのパス設定
#Thunderbirdを起動してヘルプのデバッグ情報にプロファイルフォルダを表示するボタンがある。
path_mailbox = r"C:/Users/kabay/AppData/Roaming/Thunderbird/Profiles/hlf0zypj.default-release/Mail/pop.gmail.com/mail4python"
#メールファイルへのアクセス、内容読み出し
try:
for message in mailbox.mbox(path_mailbox):
# 件名を取得
subject = message['subject']
# 差出人を取得
from_address = message['from']
# 本文を取得(マルチパートの場合を考慮)
body = ""
if message.is_multipart():
for part in message.walk():
content_type = part.get_content_type()
if content_type == 'text/plain':
body = part.get_payload(decode=True).decode()
break
else:
body = message.get_payload(decode=True).decode()
print("---top--------------------")
print(f"件名: {subject}")
print(f"差出人: {from_address}")
print(f"本文:\n{body}\n")
print("---end--------------------")
except FileNotFoundError:
print(f"ファイルが見つかりません: {path_mailbox}")
except Exception as e:
print(f"エラーが発生しました: {e}")