Q: Gmail API: Search for an existing thread with the subject line and if it exists reply to the thread, otherwise send a fresh email in python I am trying to use gmail api to reply to existing thread (if it exists) or otherwise start a new email thread.
Here is what I found:
x = gmailClient.service.users().threads().list(userId='me',q='from:noreply-dv360@google.com subject:"Report #234354 : "Reporting" from Sneha"').execute().get('threads', [])

but this returns me a list of array which look like this:
{'id': '177ed7354840ddae1', 'snippet': '-- <b>Report</b> Name: <b>Reporting</b> Account: DBM (21324356) <b>Report</b> ID: <b>34565</b> File Name: Reporting_1234354', 'historyId': '232456'}

I want to reply to the given thread... So here's my two major questions:

*

*How to fetch the thread Id of a thread by it's subject line?

*How to reply to a thread by it's thread id?

Edit 1:
def send_email(self,sender, to, subject, message_text, cc = None,messageType = "plain"):

        queryParam = f'from: me subject: "{subject}"'

        message = MIMEText(message_text,messageType)
        message['to'] = to
        message['from'] = sender
        message['subject'] = subject

        if cc != None:
            message['cc'] = cc
        
        emailBody = {'raw': base64.urlsafe_b64encode(bytes(message.as_string(),"utf-8")).decode("utf-8")}

        threadSearch = self.service.users().threads().list(userId='me',q=queryParam, maxResults = 1).execute().get('threads', [])

        if len(threadSearch):
            threadSearch = threadSearch[0]
            emailBody["threadId"] = threadSearch["id"]
            messageId = self.getMessageIdFromThread(threadSearch)
            emailBody['subject'] = subject
            emailBody["Reference"] = messageId
            emailBody["In-Reply-To"] = messageId
            print("Response: ")
            response = self.service.users().messages().send(userId = 'me', body = emailBody).execute()
        else:
            response = self.service.users().messages().send(userId = 'me', body = emailBody).execute()
        return response


    def getMessageIdFromThread(self, thread):

        tdata = self.service.users().threads().get(userId="me", id=thread['id']).execute()
        msg = tdata['messages'][0]['payload']

        for eachMsg in msg['headers']:
            if eachMsg['name'] == "Message-Id":
                return eachMsg["value"]
        
        return False

Here are the changes I did... Now This is what I get:
From Sender Side:

At Receiver End:

For some reason, the threading doesn't happen to the reciever end. Can someone guide me where exactly am I going wrong?
