How to Beginner · 3 min read

How to build AI email categorizer

Quick answer
Use a large language model like gpt-4o to classify emails by sending the email text as input and prompting the model to assign categories. Implement this by calling client.chat.completions.create with a prompt that instructs the model to categorize the email content.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the OpenAI Python SDK and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

This example shows how to send an email text to gpt-4o and get a category label such as "Spam", "Promotion", or "Personal".

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

email_text = """Subject: Huge discounts on electronics!

Dear customer, check out our exclusive deals on laptops and phones. Limited time offer!"""

prompt = f"Categorize the following email into one of these categories: Spam, Promotion, Personal, Work.\n\nEmail:\n{email_text}\n\nCategory:" 

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

category = response.choices[0].message.content.strip()
print(f"Email category: {category}")
output
Email category: Promotion

Common variations

  • Use claude-3-5-sonnet-20241022 for potentially better classification accuracy.
  • Implement async calls with asyncio for batch processing.
  • Use streaming completions for real-time categorization feedback.
  • Expand categories or use embeddings + vector search for more complex classification.

Troubleshooting

  • If you get empty or irrelevant categories, refine the prompt to be more explicit.
  • Check your API key environment variable if authentication errors occur.
  • For rate limits, implement exponential backoff retries.
  • Ensure email text is clean and well formatted for best results.

Key Takeaways

  • Use gpt-4o with clear prompts to categorize emails effectively.
  • Always keep your API key secure using environment variables.
  • Experiment with different models like claude-3-5-sonnet-20241022 for improved accuracy.
  • Prompt engineering is critical to get precise category labels.
  • Handle API errors and rate limits gracefully in production.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗