Integrating GPT with Gmail API for draft emails

Hi and welcome to the developer forum!

One of the main reasons you might be seeing a high token count for a one-line email could be due to the raw format of the email content you’re extracting. Email headers, metadata, MIME boundaries, etc. can bloat the content significantly.

Try doing:

def get_email_message(service, message_id):
    try:
        message = service.users().messages().get(userId='me', id=message_id).execute()
        
        # Extracting only the body part
        parts = message['payload']['parts']
        for part in parts:
            if part['mimeType'] == 'text/plain':
                body_data = part['body']['data']
                email_body = base64.urlsafe_b64decode(body_data.encode('UTF-8')).decode('UTF-8')
                return email_body
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None

You’re not creating a draft of the outgoing email so it’s not being sent, try adding something like

def save_as_draft(service, subject, body):
    message = base64.urlsafe_b64encode((f"Subject: {subject}\n\n{body}").encode("utf-8")).decode("utf-8")
    draft = {"message": {"raw": message}}
    try:
        result = service.users().drafts().create(userId='me', body=draft).execute()
        print(f"Draft saved with ID: {result['id']}")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

In the main function, after generating a response, save it as a draft:

print("OpenAI's response based on the email content:")
print(response_content)

# Save the response as a draft
save_as_draft(service, "Automated Response", response_content)