[Python] Turn Gmail into an Automated Alert System

[Python] Turn Gmail into an Automated Alert System

[Python] Turn Gmail into an Automated Alert System

 

In today’s world of ever-growing email notifications, manually checking important emails can be inefficient. Imagine a script that scans your Gmail inbox, looks for specific keywords, and automatically posts alerts to Slack or sends you an SMS. With Python and IMAP, you can turn Gmail into your personal alert system. In this post, we’ll walk through building a fully functional automation script using Python, Gmail, and third-party APIs.

1. Connecting to Gmail via IMAP

To interact with Gmail programmatically, we’ll use the Internet Message Access Protocol (IMAP). Python’s built-in imaplib library makes this easy. But first, you need to enable IMAP access and generate an App Password if you have 2FA enabled.

import imaplib
import email
from email.header import decode_header

# Gmail settings
imap_host = 'imap.gmail.com'
email_user = 'your_email@gmail.com'
app_password = 'your_app_password'  # Use App Password, not your login password

# Establish connection
mail = imaplib.IMAP4_SSL(imap_host)
mail.login(email_user, app_password)
mail.select('inbox')

Once connected, you can search for unread messages or any other filter criteria. For instance:

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

This will return a list of unread email IDs. We’ll process these next.

2. Parsing Emails and Matching Keywords

Once you identify which emails to check, the next task is reading their content and checking for specific keywords.

# Keywords to look for
keywords = ["urgent", "failed", "alert"]

for eid in email_ids:
    _, msg_data = mail.fetch(eid, '(RFC822)')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            msg = email.message_from_bytes(response_part[1])
            subject = decode_header(msg['Subject'])[0][0]
            if isinstance(subject, bytes):
                subject = subject.decode()
            
            body = ""
            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True).decode()
                        break
            else:
                body = msg.get_payload(decode=True).decode()

            if any(keyword in body.lower() for keyword in keywords):
                print(f"Matched keyword in subject: {subject}")

This code loops through new emails and checks if the body contains any alert keywords. If matched, we move on to triggering alerts.

3. Sending Alerts via Slack

Slack is a popular platform for team communications. You can send messages to a Slack channel using incoming webhooks. First, create an Incoming Webhook URL in your Slack workspace.

import requests

slack_webhook_url = 'https://hooks.slack.com/services/your/webhook/url'

def send_slack_alert(subject, body):
    payload = {
        "text": f"*ALERT: {subject}*\n{body}"
    }
    response = requests.post(slack_webhook_url, json=payload)
    if response.status_code == 200:
        print("Slack alert sent successfully!")
    else:
        print("Failed to send Slack alert.")

Simply call send_slack_alert(subject, body) when your keyword condition is met.

4. Sending SMS via Twilio

If you prefer real-time alerts on your phone, Twilio makes sending SMS from Python seamless. Make sure to set up a Twilio account and grab your credentials.

from twilio.rest import Client

account_sid = 'your_twilio_sid'
auth_token = 'your_twilio_auth_token'
twilio_from_number = '+1234567890'
to_number = '+1987654321'

client = Client(account_sid, auth_token)

def send_sms_alert(subject):
    message = client.messages.create(
        body=f"Email Alert: {subject}",
        from_=twilio_from_number,
        to=to_number
    )
    print(f"SMS sent with SID: {message.sid}")

This gives you full control over when and how to be notified. Use SMS for high-priority alerts, and Slack for everything else.

5. Automation & Deployment Tips

To make your alert system truly automatic, consider running the script on a schedule using cron on Unix or Task Scheduler on Windows.

# crontab to run check_gmail.py every 5 minutes
*/5 * * * * /usr/bin/python3 /path/to/check_gmail.py

Extra tips for optimization and robustness:

  • Use environment variables for credentials instead of hardcoding them.
  • Add logging instead of plain print statements for better observability.
  • Limit the message size you process — skipping large attachments or HTML parts.
  • Acknowledge processed messages with Gmail labels or mark them as read using IMAP.

By implementing these strategies, you make your automation safe, repeatable, and production-friendly.

Conclusion

With less than 100 lines of Python, you can build a mini notification engine tailored to your needs. Integrating Gmail with external alert systems allows you to surface important information quickly without being buried under noise. From sysadmins monitoring for downtimes to product managers tracking user feedback keywords, the use cases are endless. Now it’s your turn to customize the script and make email work for you!

 

Useful links: