0

目的
自分のメールアドレスに届いたメールに対して、返信を行いたいです。
自分宛に届いたメールを自分に返信して、自動でリマインドさせるようなイメージになります。

コード

account = "hogehoge@gmail.com"
password = "hogehoge"

s_title = str("メールテスト")

mail=imaplib.IMAP4_SSL('imap.gmail.com',993)
mail.login(account,password)
mail.select('inbox')

term = s_title.encode("utf-8")
print(term)
mail.literal = term
type,data=mail.search("utf-8", "SUBJECT")

for i in data[0].split():
    ok,x=mail.fetch(i,'RFC822')
    ms=email.message_from_string(x[0][1].decode('UTF-8'))

    ad=email.header.decode_header(ms.get('From'))
    ms_code=ad[0][1]

    fromObj = email.header.decode_header(ms.get('From'))
    addr = ""
    
    for f in fromObj:
        if isinstance(f[0],bytes):
            addr += f[0].decode(ms_code)
        else:
            addr += f[0]
            print(addr)

    subject = email.header.decode_header(ms.get('Subject'))
    title = ""

    for sub in subject:
        if isinstance(sub[0],bytes):
            title += sub[0].decode(ms_code)
        else:
            title += sub[0]
            print(title)

    if ms.is_multipart():
        for payload in ms.get_payload():
            if payload.get_content_type() == "text/plain":
                body = payload.get_payload()

            else:
                if ms.get_content_type() == "text/plain":
                    body = ms.get_payload()

new = MIMEMultipart()
new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = account
new["References"] = original["Message-ID"]
new["Subject"] = original["Subject"]
new["To"] = original["Reply-To"] or original["From"]
new["From"] = account

new.attach(MIMEMessage(original) )

s = smtplib.SMTP("smtp.gmail.com", 587)
s.starttls()
s.login(account, password)
s.send_message(new)
s.quit()

一度メールを検索して、タイトル等をそのまま返信しようとしているのですが、返信ではなく新しいメールとして作成されてしまいます。
スレッドIDなどを読み込むことも考えたのですがIDが変わることもあるため、この方法をとっておりました。
APIを個人的理由で使用できないため、API以外の方法を探しております)

メール返信に関する情報があまり見つからずご教授いただければ幸いです。

1 件の回答 1

0

実際に試したわけではなく少し調べた程度ですが、例えば以下の記事では Gmail での返信には "threadId" と "RFC 2822形式のメッセージID" が必要と解説しています。

Python版Gmail API ClientでThreadにメール(返信)を送信する

Gmail API referenceのusers.messages に、Threadにメールをつなげる条件は

The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met:

  1. The requested threadId must be specified on the Message or Draft.Message you supply with your request.
  2. The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard.
  3. The Subject headers must match.

と書いてあります。ここで必要な情報は

  • threadId
  • RFC 2822形式のメッセージID

の2つです。Thread単位だけでなく、Thread内のどのメールに返信するかまで指定することが必要です。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。