📧 Lesson 4.2: Automating Email Responses


🎯 Lesson Objective

By the end of this lesson, you will be able to:

  • Connect your AI agent to an email inbox

  • Automatically read and analyze incoming emails

  • Generate smart, relevant email replies using an LLM

  • (Optionally) send the responses automatically or save them for review

This creates an AI-powered email assistant that saves time, boosts efficiency, and improves customer communication.


🧠 Why Automate Email Responses?

Businesses often receive:

  • Repetitive customer inquiries (returns, support, appointments)

  • Internal requests (updates, approvals, reports)

Manual handling is:

  • 🕒 Time-consuming

  • ❌ Prone to inconsistency

AI-driven replies are:

  • ⏱️ Faster

  • 🤖 Consistent and polite

  • 📚 Can use business-specific knowledge (via RAG)


🧰 Tools You’ll Use

Tool Purpose
imaplib, email, smtplib Read & send emails in Python
LangChain + LLM (OpenAI or Ollama) Generate smart replies
RAG or preloaded context Optional – answer from company data
Streamlit (Optional) UI for review or manual approval

🔧 Step-by-Step Guide: Automate Email Responses


✅ 1. Connect to Email Server (IMAP)

import imaplib
import email

EMAIL = "[email protected]"
PASSWORD = "your_password"
IMAP_SERVER = "imap.gmail.com"  # Adjust based on your provider

# Connect and select inbox
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL, PASSWORD)
mail.select("inbox")

✅ 2. Read Unread Emails

status, messages = mail.search(None, 'UNSEEN')
email_ids = messages[0].split()

latest_id = email_ids[-1]
status, msg_data = mail.fetch(latest_id, "(RFC822)")

raw_email = msg_data[0][1]
msg = email.message_from_bytes(raw_email)

subject = msg["subject"]
from_email = msg["from"]

# Get email body
if msg.is_multipart():
    for part in msg.walk():
        if part.get_content_type() == "text/plain":
            body = part.get_payload(decode=True).decode()
else:
    body = msg.get_payload(decode=True).decode()

✅ 3. Generate an AI-Powered Reply

from langchain.llms import Ollama
from langchain.prompts import PromptTemplate

llm = Ollama(model="mistral")

template = """
You are a polite and professional email assistant.

Reply to the following customer email. Keep the tone friendly and helpful.

Email: {customer_email}

Reply:
"""

prompt = PromptTemplate(input_variables=["customer_email"], template=template)
reply = llm(prompt.format(customer_email=body))

print("✉️ Suggested Reply:n", reply)

✅ 4. Send the Reply (SMTP)

import smtplib
from email.mime.text import MIMEText

SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587

msg_reply = MIMEText(reply)
msg_reply["Subject"] = "Re: " + subject
msg_reply["From"] = EMAIL
msg_reply["To"] = from_email

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
    server.starttls()
    server.login(EMAIL, PASSWORD)
    server.sendmail(EMAIL, from_email, msg_reply.as_string())

🧪 Example Use Cases

Scenario AI Reply Example
Return request “We’re sorry to hear that. Please follow these steps to initiate a return…”
Appointment reschedule “No problem! Here are the available slots this week…”
Password issue “You can reset your password using this link: …”

🧠 Optional Add-Ons

Feature Description
✅ Review UI Use Streamlit to approve replies before sending
🧠 Context-aware reply Add internal docs or FAQ to improve answer quality
🧾 Logging Save responses and logs per sender/email
🔁 Schedule Use cron or Airflow to run this every 5–10 minutes

✅ 5. Streamlit Interface (Optional Review UI)

import streamlit as st

st.title("📬 Email Auto-Reply Assistant")
st.markdown("Subject: " + subject)
st.text_area("Email body", body)
st.text_area("AI-generated reply", reply)

if st.button("Send reply"):
    # trigger send via SMTP
    st.success("Reply sent successfully!")

✅ Summary

Step What You Did
📥 Read new emails Using imaplib and email libraries
🧠 Used LLM To generate helpful replies
✉️ Sent reply Through SMTP
🧪 Optional Used Streamlit for manual review

🔐 Note on Security

Never hard-code real passwords. Use:

  • .env files + python-dotenv

  • Secure vaults or cloud secrets

  • OAuth for Gmail if available


 

57