目的
自分のメールアドレスに届いたメールに対して、返信を行いたいです。
自分宛に届いたメールを自分に返信して、自動でリマインドさせるようなイメージになります。
コード
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以外の方法を探しております)
メール返信に関する情報があまり見つからずご教授いただければ幸いです。