The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a Python assistant to summarize emails

Here’s a simple yet functional Python assistant to summarize emails. This script connects to an email account via IMAP, fetches the latest emails, and uses a summarization model to generate concise summaries of the email bodies.

Requirements

  • imaplib and email (built-in)

  • openai (for summarization)

  • dotenv (for storing credentials securely, optional)


🐍 Python Code for Email Summarization Assistant

python
import imaplib import email from email.header import decode_header import openai import os from dotenv import load_dotenv # Load environment variables (for API key and email credentials) load_dotenv() EMAIL_USER = os.getenv("EMAIL_USER") EMAIL_PASS = os.getenv("EMAIL_PASS") IMAP_SERVER = os.getenv("IMAP_SERVER", "imap.gmail.com") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") openai.api_key = OPENAI_API_KEY def clean_subject(subject): if subject is None: return "No Subject" decoded, charset = decode_header(subject)[0] if isinstance(decoded, bytes): return decoded.decode(charset or 'utf-8', errors='ignore') return decoded def get_email_summary(body): try: response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": "You are an assistant that summarizes email content."}, {"role": "user", "content": f"Summarize this email:nn{body}"} ], max_tokens=150, temperature=0.5, ) return response['choices'][0]['message']['content'].strip() except Exception as e: return f"Error summarizing email: {e}" def fetch_and_summarize_emails(limit=5): mail = imaplib.IMAP4_SSL(IMAP_SERVER) mail.login(EMAIL_USER, EMAIL_PASS) mail.select("inbox") status, messages = mail.search(None, "ALL") email_ids = messages[0].split()[-limit:] summaries = [] for num in reversed(email_ids): status, data = mail.fetch(num, "(RFC822)") raw_email = data[0][1] msg = email.message_from_bytes(raw_email) subject = clean_subject(msg.get("Subject")) from_ = msg.get("From") body = "" if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() if content_type == "text/plain" and part.get("Content-Disposition") is None: body = part.get_payload(decode=True).decode(errors="ignore") break else: body = msg.get_payload(decode=True).decode(errors="ignore") summary = get_email_summary(body) summaries.append({ "from": from_, "subject": subject, "summary": summary }) mail.logout() return summaries # Example usage if __name__ == "__main__": email_summaries = fetch_and_summarize_emails() for idx, summary in enumerate(email_summaries, 1): print(f"nEmail {idx}") print(f"From: {summary['from']}") print(f"Subject: {summary['subject']}") print(f"Summary: {summary['summary']}")

🔐 .env Example

ini
EMAIL_USER=your_email@gmail.com EMAIL_PASS=your_app_password OPENAI_API_KEY=your_openai_key IMAP_SERVER=imap.gmail.com

🔧 Notes

  • For Gmail, use an App Password with 2FA enabled.

  • This script summarizes only the plain text portion.

  • It uses OpenAI’s GPT model for summarization — you can swap in other models or services (like Hugging Face or spaCy) as needed.

Let me know if you want a GUI version, email filtering options, or integration with other services.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About