Python imaplibでメール受信

import imaplib
import email
from email.header import decode_header, make_header

# メールをサーバーに接続する
mail = imaplib.IMAP4_SSL('xxxx.xserver.jp', 993)
mail.login('メールアドレス', 'パスワード')

# 届いたメールを確認するためにinboxを選択。
mail.select('inbox')

# //メールを一覧取得しtype変数とdata変数に代入
type, data = mail.search(None, 'ALL')

# // ループを開始
for i in data[0].split():
    # // メールをデコードする
    ok, x = mail.fetch(i, 'RFC822')
    ms = email.message_from_string(x[0][1].decode('iso-2022-jp'))

    # // 取得したデータを変数に入れる。
    to_ = str(make_header(decode_header(ms["To"])))
    date_ = str(make_header(decode_header(ms["Date"])))
    from_ = str(make_header(decode_header(ms["From"])))
    subject_ = str(make_header(decode_header(ms["Subject"])))

# // マルチパート処理
# // マルチパートじゃなかった場合
if ms.is_multipart() is False:
    payload = ms.get_payload(decode=True)
    charset = ms.get_content_charset()

    if charset is not None:
        payload = payload.decode(charset, "ignore")

# // それ以外(マルチパートだった場合)
else:
    for part in ms.walk():
        payload = part.get_payload(decode=True)
        if payload is None:
            continue
        charset = part.get_content_charset()
        if charset is not None:
            payload = payload.decode(charset, "ignore")

    # // デバック用だけど内容を表示する
    print(to_)
    print(date_)
    print(from_)
    print(subject_)
    print(payload)
投稿日:
カテゴリー: Python

コメントする

メールアドレスが公開されることはありません。

CAPTCHA