How to use AI to process emails automatically
Quick answer
Use an AI language model like
gpt-4o to automatically read and classify emails by extracting key information and generating responses. Integrate with email APIs (e.g., Gmail API) to fetch emails, then send the email content to the AI model for processing and automation.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0Access to an email API (e.g., Gmail API) with OAuth2 credentials
Setup
Install the OpenAI Python SDK and set your API key as an environment variable. Also, set up access to your email provider's API (like Gmail API) to fetch emails programmatically.
pip install openai google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client Step by step
This example fetches unread emails from Gmail, sends the email content to gpt-4o for summarization and classification, then prints the AI-generated summary and suggested action.
import os
from openai import OpenAI
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Load Gmail API credentials (assumes token.json exists from OAuth flow)
creds = Credentials.from_authorized_user_file('token.json', ['https://www.googleapis.com/auth/gmail.readonly'])
service = build('gmail', 'v1', credentials=creds)
# Fetch unread emails
results = service.users().messages().list(userId='me', labelIds=['UNREAD'], maxResults=5).execute()
messages = results.get('messages', [])
for msg in messages:
msg_data = service.users().messages().get(userId='me', id=msg['id'], format='full').execute()
parts = msg_data['payload'].get('parts', [])
body = ''
for part in parts:
if part['mimeType'] == 'text/plain':
import base64
body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')
break
prompt = f"You are an email assistant. Summarize this email and suggest a category (e.g., urgent, spam, personal, work):\n\n{body}"
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
print("Email summary and category:")
print(response.choices[0].message.content)
print("---") output
Email summary and category: This email is a meeting request for next Tuesday regarding the Q2 project update. Category: Work ---
Common variations
- Use
gpt-4o-minifor faster, cheaper processing with slightly less accuracy. - Implement asynchronous calls with
asynciofor handling large volumes of emails. - Stream responses for real-time processing using streaming endpoints if supported.
- Integrate with other email providers by adapting the API calls (e.g., Microsoft Graph API for Outlook).
Troubleshooting
- If emails are not fetched, verify OAuth token permissions and refresh tokens.
- If the AI returns irrelevant summaries, refine the prompt with clearer instructions.
- For rate limits, implement exponential backoff or batch processing.
- Ensure environment variables are correctly set to avoid authentication errors.
Key Takeaways
- Use
gpt-4oto extract summaries and classify emails automatically. - Combine email provider APIs with AI for end-to-end email automation workflows.
- Refine prompts to improve AI understanding and output relevance.
- Handle API rate limits and authentication carefully for reliable automation.