I\'m trying to automate the creation of drafts via the Gmail API, and I want these drafts to be responses to existing emails. To do this, I believe I need to set the \"threa
Actually, it's a lot simpler than that! If you just supply the correct Subject in the headers, and the correct threadId in the body, Google will calculate all the references for you.
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()
This results in a draft, ready to be sent in the correct thread:
Then, I send the mail. As you can see, the references are calculated for you:
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.
if you want to not only create the draft but also additionally send it then extension of above code (one additional line after draft =...create().execute():
draft = service.users().drafts().create(userId="me", body= message).execute()
message = service.users().drafts().send(userId='me', body={'id': draft['id']}).execute()