This python script drafts AI responses to incoming emails in Gmail.
Note: this is the companion code to this Medium post and is therefore optimized to be easy to understand. Making it production ready will require additional changes. See further down.
- It opens up a browser window (unless valid credentials are found in
token.pickle
) to sign in with Google - It fetches Inbox emails received in the last hour
- For each email:
- It extracts Subject, Content (using mailparser) and ThreadId
- It assesses if the email requires a response (using gpt-4o)
- If it does, it generates a reply (using gpt-4-turbo)
- Finally it creates a draft reply to the initial conversation
- Setup Google OAuth for Gmail API with the modify scope. Download the
credentials.json
file and add it to the repository (more details). - Install necessary libraries.
pip install -r requirements.txt
- Set up the OPENAI_API_KEY env variable.
export OPENAI_API_KEY="Your_OpenAI_API_Key"
- Execute the script to sign in to Google and start processing emails.
python app.py
- To keep this script running hourly, set up a cron job.
0 * * * * /usr/bin/python3 /path/to/email-responder/app.py
- Relies on a cron job rather than subscriptions.
- Does not consider other emails in the thread.
- Does not learn from past conversations.
- Does not embed text from previous emails in responses.
- Responses may sound too much like ChatGPT.
If the basic functionalities of this script don't meet all your needs, consider checking out MailFlowAI.com. I developed MailFlow to help small businesses efficiently respond to customer emails.
Unlike the basic script, MailFlow offers enhanced capabilities to handle complex email threads, adapt the response tone to match your brand, and learn from diverse data sources like your company website, previous email interactions, and relevant documents.