get the latest email in the thread


You need to get the last message out of the thread array returned by users: threads.list.

More Information:

As per the documentation, the users: threads.list method returns an array of Message resources per thread. A representation of this resource is as follows:

  "threads": [
      "id": string,
      "snippet": string,
      "historyId": string,
      "messages": [
          object (Message)
  "nextPageToken": string,
  "resultSizeEstimate": integer

The messages array contain all the messages in the thread, ordered by internalDate.

The internalDate value os this response is defined as such:

internalDate: string (int64 format)

The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the Date header. However, for API-migrated mail, it can be configured by client to be based on the Date header.

Knowing that messages with higher internalDate values are more recent, we can use this to retrieve the latest email in the thread:

messages = service.users().threads().list(userId='me').execute().get('threads', [])

for message in messages:
    if search in message['snippet']:
        # add/modify the following lines:
        thread = service.users().threads().get(userId='me', id=message['id'], fields='messages(id,internalDate)').execute() #.get( [])
        last = len(thread['messages']) - 1
        message_id = thread['messages'][last]['id']

        # non-modified code:
        full_message = service.users().messages().get(userId='me', id=message_id, format="raw").execute()
        msg_str = base64.urlsafe_b64decode(full_message['raw'].encode('ASCII'))
        mime_msg = email.message_from_bytes(msg_str)
        y = re.findall(r'Delivered-To: (\S+)', str(mime_msg))


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top