I'm attempting to send an existing email to another thread using the gmail API in Flask.
Context:
I've created a new message object and successfully made the In-Reply-To
, References
and threadId
equal the message_id
and thread_id
respectively. (Following Gmail's API reference)
def create_message(sender, to, subject, thread_id, message_id, message_text, service):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
if type(message_text) != str:
message_text = str(message_text)
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
message['In-Reply-To'] = message_id
message['References'] = message_id
message['threadId'] = thread_id
print('created message threadId: %s does == ..' %message['threadId'])
print(thread_id)
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
messages = service.users().messages()
send = messages.send(userId='me', body=body).execute()
Problem:
I'm able to successfully send the new messages to my inbox but they are created with a new threadId
even though the print statement in the above code shows the same threadId
.
Then, when I follow the code example from this thread:
body = {'message': {'raw': raw, 'threadId': thread_id}}
I get the following error:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "'raw' RFC822 payload message string or uploading message via /upload/* URL required">
Question:
How can I generate these emails so they thread with the same threadId
?
Note: I have found similar questions here for javascript, and here for java but haven't found an answer for python.