This blog post is totally technical and just here to help fellow developers who might encounter the same issue.
If you are looking to hire a python developer, check out this outsourcing firm.
Problem
When working with the Gmail API to import messages, you first get a list of messages (with their associated ids
) and then use those ids
to get the email’s data, like this:
- List messages to get
message_id
's - Get message using the
message_id
- Do something with the message
But sometimes, when you call the Gmail API with a message id
you just fetched using the list() method, you get an error saying: Requested entity was not found
.
How come Gmail can’t find a message it just told you exists?
Especially when the message actually exists! You can use the following link to see if one of your message exists using the message_id
:
https://mail.google.com/mail/u/0/#inbox/<MESSAGE_ID>
If the message does not exist when you search for it using the link above, then it actually does not exist (like a draft that was deleted)
Solution
The id
of a message actually seems to change in some cases - not that immutable. I haven’t fully investigated as this is out of scope but when a message gets a reply, it moves from being a simple message to being a thread - and in that case, sometimes the id
changes.
When you get a list of messages, take the message id
and the thread id
.
If the message.get()
method from the API doesn’t work with the message id
, use the threads.get()
method (documentation here) to get the updated message id
and retry to get the message with that new id
.
This will solve it! To summarize:
- Get message and thread
ids
using themessages.list()
method - Try to get the message using the
message id
- If it doesn’t work, get the new
message id
usingthreads.get()
- Try to get the message again with the new
message id
Hope that helps!