≡ Menu

Build an AI Email Summarizer Bot with Python and Gemini 🤖

Feeling overwhelmed by your inbox?

Wish you could get a quick summary of your unread emails without opening them all?

With the power of Python and Google’s Gemini AI, you can build a simple bot that does just that.

This tutorial will walk you through setting up and running a Python script that connects to your Gmail account, finds unread emails, and sends you a concise, AI-generated summary of each one.

1. Get Your Tools Ready 🛠

Before we dive into the code, you’ll need to set up a few things. Don’t worry, it’s quick and easy!

  • Python: Make sure you have Python installed on your computer. You can download it from the official Python website.
  • Google App Password: For security, you can’t use your regular Gmail password in the script. Instead, you’ll need to generate a special “app password.” Go to your Google Account security settings, enable 2-Step Verification, and then create an App Password for the “Mail” app on your computer.
  • Google AI Studio API Key: Our bot will use Google’s Gemini Pro model to summarize the emails. You can get an API key for free by signing up for Google AI Studio.
  • Install Libraries: Open your terminal or command prompt and run the following command to install the necessary Python libraries:

     

    pip install google-generativeai==0.6.0
    pip install imaplib
    pip install email
    

 

2. The Python Code: Your AI Bot Blueprint

 

Now, let’s create the bot itself. Copy the following code and save it in a file named email_bot.py.

import imaplib
import email
import google.generativeai as genai
import smtplib
from email.mime.text import MIMEText

# --- Configuration ---
# Your Gmail account credentials and server details
GMAIL_USER = "your_email@gmail.com"
GMAIL_APP_PASSWORD = "your_app_password"  # Use the app password you generated
IMAP_SERVER = "imap.gmail.com"
SMTP_SERVER = "smtp.gmail.com"
PORT = 993  # IMAP SSL port
SMTP_PORT = 587 # SMTP TLS port

# Your Google AI Studio API Key
GOOGLE_API_KEY = "your_google_api_key"

# The email address to which summaries will be sent
TARGET_EMAIL = "your_personal_email@example.com"

# --- Function to get emails ---
def get_unread_emails():
    """Connects to Gmail and fetches all unread emails."""
    try:
        mail = imaplib.IMAP4_SSL(IMAP_SERVER, PORT)
        mail.login(GMAIL_USER, GMAIL_APP_PASSWORD)
        mail.select("inbox")
        
        # Search for all unread emails
        status, messages = mail.search(None, "(UNSEEN)")
        
        email_messages = []
        for num in messages[0].split():
            status, data = mail.fetch(num, "(RFC822)")
            email_messages.append(data[0][1].decode("utf-8"))
            
        mail.close()
        mail.logout()
        return email_messages
    except Exception as e:
        print(f"Error connecting to Gmail: {e}")
        return []

# --- Function to summarize email with Gemini Pro ---
def summarize_with_gemini(email_content):
    """Uses the Gemini Pro model to summarize the email content."""
    genai.configure(api_key=GOOGLE_API_KEY)
    model = genai.GenerativeModel('gemini-pro')

    prompt = (
        f"You are a helpful assistant that summarizes emails. "
        f"Provide a concise summary of the following email, focusing on the main points and any action items:\n\n"
        f"--- Email Content ---\n"
        f"{email_content}"
    )

    try:
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        print(f"Error calling Gemini API: {e}")
        return "Could not generate a summary."

# --- Function to send an email ---
def send_summary_email(subject, body, to_address):
    """Sends an email using SMTP."""
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = GMAIL_USER
    msg['To'] = to_address
    
    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # Secure the connection
            server.login(GMAIL_USER, GMAIL_APP_PASSWORD)
            server.sendmail(GMAIL_USER, to_address, msg.as_string())
        print(f"Successfully sent summary email to {to_address}")
    except Exception as e:
        print(f"Error sending email: {e}")

# --- Main Bot Logic ---
if __name__ == "__main__":
    print("Fetching unread emails...")
    unread_emails_raw = get_unread_emails()
    
    if not unread_emails_raw:
        print("No new unread emails found.")
    else:
        print(f"Found {len(unread_emails_raw)} unread email(s).")
        
        for email_raw in unread_emails_raw:
            msg = email.message_from_string(email_raw)
            subject = msg.get("Subject", "No Subject")
            
            # Find the plain text part of the email body
            email_body = ""
            if msg.is_multipart():
                for part in msg.walk():
                    content_type = part.get_content_type()
                    if content_type == "text/plain":
                        email_body = part.get_payload(decode=True).decode()
                        break
            else:
                email_body = msg.get_payload(decode=True).decode()

            print(f"\nProcessing email with subject: '{subject}'")
            
            # Get summary from the AI
            summary = summarize_with_gemini(email_body)
            
            # Send the summary to your personal email
            summary_subject = f"AI Summary: {subject}"
            summary_body = f"Original Subject: {subject}\n\nSummary:\n{summary}"
            
            send_summary_email(summary_subject, summary_body, TARGET_EMAIL)
            
            # NOTE: The bot does not mark emails as "read" to allow for multiple runs
            # without manual intervention, but you could add this feature if desired.

 

3. Customize and Run Your Bot 🚀

 

  1. Replace the placeholders: In the Configuration section at the top of the script, replace the placeholder values with your own information:
    • GMAIL_USER: Your Gmail email address.
    • GMAIL_APP_PASSWORD: The app password you generated.
    • GOOGLE_API_KEY: Your API key from Google AI Studio.
    • TARGET_EMAIL: The email address where you want to receive the summaries. This could be the same as your Gmail address.

 

  1. Run the script: Open your terminal, navigate to the directory where you saved email_bot.py, and run the script with the following command:

     

    python email_bot.py
    
  2. Check your inbox: If you have any unread emails, the bot will start processing them. You’ll see a message for each one in the terminal, and then you’ll receive a new email at your TARGET_EMAIL with the AI-generated summary.

 

How It All Works

 

This bot is powered by a few key components:

  • IMAP: The Internet Message Access Protocol is used to connect to your Gmail account and retrieve unread emails.
  • Gemini Pro: The email body is sent to Google’s Gemini Pro model, which uses a pre-written prompt to understand the request and generate a concise summary.
  • SMTP: The Simple Mail Transfer Protocol is used to send the new email containing the summary from your Gmail account to your target email address.

This is a great starting point for building more advanced AI email tools. You could modify this bot to:

  • Draft replies automatically.
  • Classify emails as urgent or non-urgent.
  • Organize emails into different folders.

Happy coding!

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments… add one }

Leave a Comment