[Python] Send email as reply using Gmail API in python

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página