title: 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
body: <p>I am trying to use gmail api to reply to existing thread (if it exists) or otherwise start a new email thread.</p>
  <p>Here is what I found:</p>
  <pre><code>x = gmailClient.service.users().threads().list(userId='me',q='from:noreply-dv360@google.com subject:&quot;Report #234354 : &quot;Reporting&quot; from Sneha&quot;').execute().get('threads', [])
  </code></pre>
  <p>but this returns me a list of array which look like this:</p>
  <pre><code>{'id': '177ed7354840ddae1', 'snippet': '-- &lt;b&gt;Report&lt;/b&gt; Name: &lt;b&gt;Reporting&lt;/b&gt; Account: DBM (21324356) &lt;b&gt;Report&lt;/b&gt; ID: &lt;b&gt;34565&lt;/b&gt; File Name: Reporting_1234354', 'historyId': '232456'}
  </code></pre>
  <p>I want to reply to the given thread... So here's my two major questions:</p>
  <ol>
  <li>How to fetch the thread Id of a thread by it's subject line?</li>
  <li>How to reply to a thread by it's thread id?</li>
  </ol>
  <p><strong>Edit 1:</strong></p>
  <pre><code>def send_email(self,sender, to, subject, message_text, cc = None,messageType = &quot;plain&quot;):
  
          queryParam = f'from: me subject: &quot;{subject}&quot;'
  
          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(),&quot;utf-8&quot;)).decode(&quot;utf-8&quot;)}
  
          threadSearch = self.service.users().threads().list(userId='me',q=queryParam, maxResults = 1).execute().get('threads', [])
  
          if len(threadSearch):
              threadSearch = threadSearch[0]
              emailBody[&quot;threadId&quot;] = threadSearch[&quot;id&quot;]
              messageId = self.getMessageIdFromThread(threadSearch)
              emailBody['subject'] = subject
              emailBody[&quot;Reference&quot;] = messageId
              emailBody[&quot;In-Reply-To&quot;] = messageId
              print(&quot;Response: &quot;)
              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=&quot;me&quot;, id=thread['id']).execute()
          msg = tdata['messages'][0]['payload']
  
          for eachMsg in msg['headers']:
              if eachMsg['name'] == &quot;Message-Id&quot;:
                  return eachMsg[&quot;value&quot;]
          
          return False
  </code></pre>
  <p>Here are the changes I did... Now This is what I get:</p>
  <p>From Sender Side:</p>
  <p><a href="https://i.stack.imgur.com/VU2Hp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VU2Hp.png" alt="enter image description here" /></a></p>
  <p>At Receiver End:</p>
  <p><a href="https://i.stack.imgur.com/tJKQ2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tJKQ2.png" alt="enter image description here" /></a></p>
  <p>For some reason, the threading doesn't happen to the reciever end. Can someone guide me where exactly am I going wrong?</p>