1

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:

  1. How to fetch the thread Id of a thread by it's subject line?
  2. 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:

enter image description here

At Receiver End:

enter image description here

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

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62
  • this might help https://stackoverflow.com/q/53149409/1841839 – Linda Lawton - DaImTo Mar 03 '21 at 10:49
  • Checked it out, but still stuck at the same point. Have added some more code for more clarification – Shivam Sahil Mar 03 '21 at 11:27
  • Where are you stuck? The post contains multiple questions. – Kessy Mar 03 '21 at 15:02
  • In the Edit 1: As I have provided, I am able to send to the thread, but it appears as a new email at receiver side. Whereas appear to be thread in sender side. – Shivam Sahil Mar 04 '21 at 05:35
  • Have you tried to send it to other emails or have you checked that the emails are displayed separated on the receivers end but are on the same thread? Can you update on it? – Kessy Mar 09 '21 at 15:09
  • I didn't exactly get you when you said `have you checked that the emails are displayed separated on the receivers end but are on the same thread`. I am sending the email on the same threadId, so they're on the same thread but are sent in new thread only at reciever end. – Shivam Sahil Mar 10 '21 at 06:27
  • Have you checked that the mail you are sending complies with [Adding drafts and messages to threads](https://developers.google.com/gmail/api/guides/threads#adding_drafts_and_messages_to_threads) – Kessy Mar 15 '21 at 16:44

0 Answers0