0

I would like to know how to send an email as a reply from a thread using the gmail API.

The code I'm currently using (but it only sends as normal email) is this: The thread_id that I'm using is somenthing like CAJvJKUbP=+NwgeyCn40X-qG1i3yq7PzmXiChjJnROSAbHye1Bg@mail.gmail.com

def create_message_with_thread_id(sender, to, subject, message_text, thread_id):
    from email.message import EmailMessage
    message = EmailMessage()

    message.set_content(message_text)

    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message['In-Reply-To'] = thread_id
    message['References'] = thread_id

    # encoded message
    encoded_message = base64.urlsafe_b64encode(message.as_bytes()) \
        .decode()

    message = {
        'raw': encoded_message,
        }

    return message
    

# Function to send the message

def send_message(service, user_id, message):
    try:
        message = service.users().messages().send(
            userId=user_id, body=message).execute()
        print("Message Id: %s" % message['id'])
        return message
    except HttpError as e:
        print("An error occurred: %s" % e)
        return None
  • Try looking at [Send Reply to email thread using Gmail API](https://stackoverflow.com/questions/53149409/send-reply-to-email-thread-using-gmail-api). – Alias Cartellano Jul 26 '23 at 21:16
  • And how can I get the thread ID? Currently I am getting an id like 'CAJvGHUYRMLVwT7AgM-3G1xOk=aNe4BhpkFDE1DHhhtNcmvT6kA@mail.gmail.com' but it should be like '18597d988248bfbd' – Daniel Schutz Jul 27 '23 at 15:07

1 Answers1

0

For the In-Reply-To and References headers you need the message id, which you can retrieve from the Message-Id header of the message you want to reply to:

message_id = previous_message['Message-Id']

message['In-Reply-To'] = message_id
message['References'] = message_id

The thread id needs to be used inside the response you are sending to the Gmail API, at the same level as the raw message:

message = {
    'raw': encoded_message,
    'threadId': thread_id
}
linkyndy
  • 17,038
  • 20
  • 114
  • 194