Search code examples
gmail-apigoogle-api-python-client

Gmail API (Python) - Unable to add a reply to the thread


I want to add a reply to a gmail thread via the API.

Google says to:

simply add a threadId key paired with a thread ID to a message's metadata, the message object.

And here's what I am trying:

def create_message(sender, to, cc, bcc, subject, message_text, file=None, thread=None):
    message = MIMEMultipart()
    print(thread)
    message['to'] = to
    if cc:
        message['cc'] = cc
    if bcc:
        message['bcc'] = bcc
    if thread:
        message['threadId'] = thread
    message['from'] = sender
    message['subject'] = subject
    msg = MIMEText(message_text, 'html')
    message.attach(msg)
    if file:
        message = attach_file(message, file)
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

But it isn't working. I'm not sure what to do.


Solution

  • I finally managed to get it working. The threadId needed to be moved from the message dictionary into the output itself.

    Hopefully this clears it up for someone else:

    def create_message(sender, to, cc, bcc, subject, message_text, file=None, thread=None):
        message = MIMEMultipart()
        message['to'] = to
        if cc:
            message['cc'] = cc
        if bcc:
            message['bcc'] = bcc
        message['from'] = sender
        message['subject'] = subject
        msg = MIMEText(message_text, 'html')
        message.attach(msg)
        if file:
            message = attach_file(message, file)
        output =  {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
        if thread:
            output['threadId'] = thread
        return output