MIME Headers 无法通过 Gmail API

MIME Headers Not Making it Through Gmail API

我正在尝试通过 Gmail API 自动创建草稿,我希望这些草稿是对现有电子邮件的回复。为此,我相信我需要设置 "threadId" header(特定于 Gmail)、"References" header 和 "In-Reply-To" header .此外,要让 Gmail 将邮件视为回复,"Subject" header 必须与原始电子邮件匹配。

我将所有这些 header 硬编码到 MIMEText object 中,然后将消息进行 base-64 编码(urlsafe)作为字符串并让 Gmail API交付它。但是,"threadId"、"In-Reply-To" 和 "References" header 似乎从未出现在发送的电子邮件中,因为它们不存在于 MIME 中在 Gmail UI 中单击 "Show original" 时显示。

new = MIMEText("reply body text")
new["In-Reply-To"] = "[Message-ID of email to reply to]" #looks like <..@mail.gmail.com>
new["References"] = "[Message-ID of email to reply to]" #looks like <..@mail.gmail.com>
new["threadId"] = "[threadId of message to reply to]" #looks like 14ec476abbce3421
new["Subject"] = "Testsend2"
new["To"] = "[Email to send to]"
new["From"] = "[Email to send from]"

messageToDraft = {'raw': base64.urlsafe_b64encode(new.as_string())}
message = {'message': messageToDraft}
draft = service.users().drafts().create(userId="me", body=message).execute()

其实比那简单多了!如果您在 headers 中提供正确的 Subject,并且在 body 中提供正确的 threadId,Google 将为您计算所有引用。

new = MIMEText("This is the placeholder draft message text.")
new["Subject"] = "Example Mail"
new["To"] = "emtholin@gmail.com"
new["From"] = "emtholin@gmail.com"

raw = base64.urlsafe_b64encode(new.as_string())
message = {'message': {'raw': raw, 'threadId': "14ec598be7f25362"}}
draft = service.users().drafts().create(userId="me", body=message).execute()

这会生成草稿,准备在正确的线程中发送:

然后,我发送邮件。可以看到,参考文献是为你计算的:

MIME-Version: 1.0
Received: by 10.28.130.132 with HTTP; Sat, 25 Jul 2015 07:54:12 -0700 (PDT)
In-Reply-To: <CADsZLRz5jWF5h=6Cs1F45QQOiFuqNGmMeb6St5e-tOj3stCNiA@mail.gmail.com>
References: <CADsZLRwmDZ_L5_zWqE8qOgoKuvRiRTWUopqssn4+XYGM_SKrfg@mail.gmail.com>
    <CADsZLRz5jWF5h=6Cs1F45QQOiFuqNGmMeb6St5e-tOj3stCNiA@mail.gmail.com>
Date: Sat, 25 Jul 2015 16:54:12 +0200
Delivered-To: emtholin@gmail.com
Message-ID: <CADsZLRxuyFhuGNPwjRrfFVQ0_2MxO=_jstjmsBGmAiwMEvfWSg@mail.gmail.com>
Subject: Example Mail
From: Emil Tholin <emtholin@gmail.com>
To: Emil Tholin <emtholin@gmail.com>
Content-Type: text/plain; charset=UTF-8

This is the placeholder draft message text.

如果您不仅要创建草稿,还要发送它,然后扩展上面的代码(草稿后多一行 =...create().execute():

    draft = service.users().drafts().create(userId="me", body= message).execute()
    message = service.users().drafts().send(userId='me', body={'id': draft['id']}).execute()