Is there a way to get the Message ID after inserting a message via the API's response?
For example, I use the below code to insert the initial message:
try:
message1 = service.users().messages().insert(userId='me', body=temp).execute()
print(f"{message1['id']} / {message1['threadId']}")
In this API call, id
and threadId
are the same, a 16 character string.
Next, I insert a reply. I go into Gmail to get the Message ID (<...@mail.gmail.com>
) and set this up in the next API call as follows:
message['subject'] = 'Re: test subject'
message['In-Reply-To'] = '<...@mail.gmail.com>'
message['References'] = '<...@mail.gmail.com>'
encoded_message = urlsafe_b64encode(message.as_bytes())
temp = {'raw': encoded_message.decode(), 'labelIds': ['UNREAD'], 'threadId': 'THREAD_ID_FROM_FIRST_CALL'}
try:
message1 = service.users().messages().insert(userId='me', body=temp).execute()
print(f"{message1['id']} / {message1['threadId']}")
The response here is a different message1['id']
but the same message1['threadId']
as above, so it shows up properly threaded in Gmail. But, is there a way to easily get Message ID from the response body? Can I generate it from message1['id']
? The alternative is to make a second API to find a message by message1['id']
but I'm trying to avoid that. Thanks.
Unfortunately, there's no direct way to retrieve the new messageId
apart from making a new API call.
This is due to the fact that messageId
and threadId
are two different parameters:
messageId
corresponding to the message in the thread
threadId
corresponding to the thread
So if you insert a new reply into a thread, the threadId
will obviously be the same as the one associated to the original message, but the new reply will receive a new id - a messageId
which is unique and has nothing to do with the threadId
associated with it.
What you can do instead is to group all the threads by their threadId
s and based on that, insert a new reply. In this way, you can also easily gather the messageId
s from that specific thread.
Reference