≡ Menu

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 }

Adding user authentication to your web application can be a daunting task.

From managing user sign-ups and logins to handling password resets and social logins, the complexity can quickly become overwhelming.

This is where Clerk comes in.

Clerk is a powerful and flexible user management platform that takes the pain out of building authentication flows.

It provides a suite of ready-to-use components and hooks that allow you to integrate secure and customizable authentication into your application in a matter of minutes, not days.

In this tutorial, we’ll walk you through everything you need to know to get started with Clerk.

We’ll cover setting up your project, installing the necessary packages, configuring your environment variables, and using Clerk’s pre-built components to add a full authentication flow to a simple React application.

By the end of this guide, you’ll have a solid understanding of how Clerk works and be able to implement it in your own projects with confidence.


What is Clerk and Why Use It?

Before we dive into the code, let’s understand what makes Clerk a great choice for authentication. Clerk isn’t just an API; it’s a complete user management platform. It offers:

  • Pre-built UI Components: Clerk provides a library of beautiful and highly customizable React components like <SignIn>, <SignUp>, and <UserProfile>. This means you don’t have to build forms and UI from scratch.
  • Secure & Compliant: Clerk handles all the security best practices for you, including password hashing, session management, and protecting against common vulnerabilities. It’s built with compliance in mind, so you don’t have to worry about the nitty-gritty details.
  • Multi-Factor Authentication (MFA) and Social Logins: Easily enable popular login methods like Google, GitHub, and email/password, as well as add an extra layer of security with MFA.
  • Flexible and Framework Agnostic: While we’ll be using React in this tutorial, Clerk supports a wide range of frameworks, including Next.js, Remix, and more.
  • Intuitive Dashboard: The Clerk dashboard is a powerful tool for managing users, monitoring activity, and configuring your authentication settings.

By using Clerk, you can focus on building your application’s core features while leaving the complex and time-consuming task of authentication to the experts.


 

Prerequisites & Initial Setup

 

To follow along with this tutorial, you’ll need the following:

  • Node.js & npm (or yarn): Make sure you have Node.js installed on your machine.
  • A text editor: VS Code is a great choice.
  • A Clerk account: Head over to clerk.com and sign up for a free account.

Let’s get our project set up. For this tutorial, we’ll be using a simple React application created with Vite.

  1. Create a new React project: Open your terminal and run the following command:
    npm create vite@latest my-clerk-app -- --template react
    cd my-clerk-app
    npm install
    
  2. Install Clerk: Now, let’s install the Clerk SDK for React.
    npm install @clerk/clerk-react
    
  3. Create a Clerk Application: Go to your Clerk dashboard. Click on “Add Application.” Give your application a name (e.g., “My Clerk App”) and choose the authentication providers you want to enable (e.g., Email, Google, GitHub). Once created, you’ll be taken to the application settings page.

Important: On your application settings page, you’ll find your Publishable Key and Secret Key. We will need the Publishable Key for our front-end application. NEVER expose your Secret Key in your front-end code.


Connecting Clerk to Your React App

Now that we have our keys, let’s connect Clerk to our React application.

  1. Create a .env file: In the root of your project, create a new file named .env. This file will store our environment variables. Add your Clerk Publishable Key to this file:
    VITE_CLERK_PUBLISHABLE_KEY=pk_your_publishable_key
    

    Note: The VITE_ prefix is crucial for Vite to expose this variable to the browser.

  2. Wrap your application with <ClerkProvider>: The <ClerkProvider> component is the entry point for all things Clerk. It makes the Clerk SDK available throughout your application. Open src/main.jsx and modify it as follows:
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { ClerkProvider } from '@clerk/clerk-react';
    import App from './App.jsx';
    import './index.css';
    
    // Get the Clerk publishable key from the environment variables
    const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
    
    // Check if the key is defined
    if (!PUBLISHABLE_KEY) {
      throw new Error("Missing Publishable Key");
    }
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <ClerkProvider publishableKey={PUBLISHABLE_KEY}>
          <App />
        </ClerkProvider>
      </React.StrictMode>
    );
    

    We’ve now successfully connected our application to Clerk. The next step is to add the user interface components.


 

Adding Clerk UI Components

 

Clerk provides several pre-built components that handle the entire authentication flow.

  1. Create a Protected Route: Let’s create a “Dashboard” component that only authenticated users can see. First, create a new file src/Dashboard.jsx.

     

    import React from 'react';
    import { UserButton, SignedIn, SignedOut } from '@clerk/clerk-react';
    
    const Dashboard = () => {
      return (
        <div className="dashboard-container">
          <h2>Welcome to your Dashboard!</h2>
          <p>This is a protected page. Only authenticated users can see this.</p>
          <UserButton afterSignOutUrl="/" />
        </div>
      );
    };
    
    export default Dashboard;
    
    • <UserButton>: This component displays a button with the user’s profile image. Clicking it opens a dropdown for managing their profile and signing out. The afterSignOutUrl prop redirects the user to the specified URL after they sign out.

 

  1. Conditional Rendering with <SignedIn> and <SignedOut>: Clerk provides special components to conditionally render content based on the user’s authentication state. Let’s use these in our src/App.jsx to show either the sign-in/sign-up forms or the dashboard.

    JavaScript

    import { SignIn, SignUp, SignedIn, SignedOut } from '@clerk/clerk-react';
    import './App.css'; // Make sure you have some basic styling
    import Dashboard from './Dashboard';
    
    function App() {
      return (
        <div className="app-container">
          <header className="app-header">
            <h1>Clerk Authentication Tutorial</h1>
          </header>
    
          <main className="app-main">
            {/* Renders if the user is signed in */}
            <SignedIn>
              <Dashboard />
            </SignedIn>
    
            {/* Renders if the user is signed out */}
            <SignedOut>
              <div className="auth-forms-container">
                <p>Please sign in or sign up to access the dashboard.</p>
                <SignIn path="/sign-in" routing="path" />
                <SignUp path="/sign-up" routing="path" />
              </div>
            </SignedOut>
          </main>
        </div>
      );
    }
    
    export default App;
    
    • <SignIn path="/sign-in" routing="path" />: This component displays the entire sign-in form, including social login options. path and routing are necessary to make it work correctly without a routing library.
    • <SignUp path="/sign-up" routing="path" />: Similar to the sign-in component, this handles the user registration process.
  2. Run your application: Open your terminal and run npm run dev. Your application should now be running. You will see the sign-in and sign-up forms. After you create a new account or sign in with a social provider, you will be automatically redirected to your dashboard page.

 

Next Steps & Conclusion

 

Congratulations! You’ve successfully implemented a full authentication flow using Clerk. This is just the beginning. From here, you can:

  • Explore other components: Check out the <UserProfile> and <OrganizationProfile> components to allow users to manage their details and teams.
  • Use Clerk Hooks: Dive into hooks like useAuth(), useUser(), and useSession() to get user information and authentication state anywhere in your app.
  • Add a backend: Learn how to verify JWT tokens on your server-side with Clerk’s backend SDKs to protect your API endpoints.
  • Customize the UI: Clerk components are highly customizable using CSS variables.

Clerk handles the complexities of authentication, so you can focus on building the features that matter. Happy coding!

{ 0 comments }