Have you ever wanted to be instantly notified when you receive an email from a specific person, or that contains a certain keyword? With the use of IMAP, Python, and webhooks, you can automate this process and integrate it with a plethora of services using platforms like IFTTT (or Any Other Webhook) . In this blog post, we’ll walk you through the steps to set this up.
Prerequisites
- A working email account that supports IMAP (most popular email services like Gmail, Yahoo, and Outlook do).
- Python is installed on your machine.
- A free account on IFTTT (if you choose to use IFTTT’s webhook service).
Step 1: Setting up IFTTT
Before we dive into the Python code, you should have your IFTTT webhook ready.
- Go to IFTTT and create a new applet.
- For the “this” part, choose the “Webhooks” service and select the “Receive a web request” trigger.
- Name your event (e.g., “email_received”).
- For the “that” part, choose any action you like (e.g., get a notification, turn on a light, etc.).
- Save the applet.
Once saved, you can find your webhook URL by going to the Webhooks service page and clicking on “Documentation”. This URL will look something like: https://maker.ifttt.com/trigger/{event}/with/key/{your_key}
.
Step 2: Python Code to Check Emails and Trigger Webhook
import imaplib
import email
import requests
# Email account details
EMAIL = 'your_email@example.com'
PASSWORD = 'your_password'
IMAP_SERVER = 'imap.example.com'
FOLDER = 'inbox'
# IFTTT webhook URL
WEBHOOK_URL = 'https://maker.ifttt.com/trigger/email_received/with/key/YOUR_KEY_HERE'
def check_email_and_trigger_webhook():
# Connect to the email server
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL, PASSWORD)
mail.select(FOLDER)
# Search for all new emails
status, email_ids = mail.search(None, 'UNSEEN')
email_ids = email_ids[0].split()
for e_id in email_ids:
# Fetch the email by ID
status, data = mail.fetch(e_id, '(RFC822)')
raw_email = data[0][1]
# Convert raw email to EmailMessage object
msg = email.message_from_bytes(raw_email)
# If a specific sender or keyword is found in the subject, trigger the webhook
if 'specific_sender@example.com' in msg['From'] or 'your_keyword' in msg['Subject']:
payload = {
'value1': msg['From'],
'value2': msg['Subject'],
'value3': msg['Date']
}
response = requests.post(WEBHOOK_URL, json=payload)
# Optional: print response from webhook
print(response.text)
# Logout and close connection
mail.logout()
# Run the function
check_email_and_trigger_webhook()
Replace placeholders (your_email@example.com
, your_password
, etc.) with your actual credentials and webhook URL.
Step 3: Running the Script
You can run the script by navigating to the directory containing the script in the terminal and executing python script_name.py
.
Now that your Python script is ready and your IFTTT applet is set up, you’re almost there. You can run the Python script on either a Raspberry Pi (if you have one) or a web server like Linode. Here’s how:
- If you have a Raspberry Pi, copy your script to the Pi and run it using
python3 your_script.py
. Make sure to keep the script running continuously to monitor incoming emails. - If you’re using a web server like Linode, upload your script to the server and execute it. You can also schedule the script to run periodically using a tool like
cron
.
Personally what I did for my use case is I handled the email filtering and forwarding on my Gmail account and if the email followed specific criteria I forwarded it to another email which I created for IFTTT usage and I use for the the below python code
import imaplib
import email
import requests
# Email server settings
IMAP_SERVER = 'imap.example.com'
EMAIL_ADDRESS = 'your_email@example.com'
EMAIL_PASSWORD = 'your_password'
# Webhook URL
WEBHOOK_URL = 'https://maker.ifttt.com/trigger/email_received/with/key/YOUR_KEY_HERE'
# Connect to the IMAP server
imap = imaplib.IMAP4_SSL(IMAP_SERVER)
imap.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
imap.select('inbox') # You can select the appropriate mailbox
# Search for unread messages
status, email_ids = imap.search(None, '(UNSEEN)')
# Process unread emails
for email_id in email_ids[0].split():
status, email_data = imap.fetch(email_id, '(RFC822)')
raw_email = email_data[0][1]
# Parse the email
msg = email.message_from_bytes(raw_email)
# Extract relevant email data
sender = msg['From']
subject = msg['Subject']
body = ""
# Get the 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()
break
else:
body = msg.get_payload(decode=True).decode()
# Trigger the webhook
payload = {
'value1': sender,
'value2': subject,
'value3': body
}
response = requests.post(WEBHOOK_URL, json=payload)
# Mark the email as read (optional)
imap.store(email_id, '+FLAGS', '(\Seen)')
# Logout from the IMAP server
imap.logout()
When it comes to enhancing your digital workflow and staying in the loop, the power of IFTTT webhooks cannot be overstated. With the ability to seamlessly connect your email alerts to platforms such as Slack, push notifications, Telegram, and a multitude of other services, you can unlock a new level of productivity and convenience. Whether you want to receive immediate notifications for vital emails, streamline your team communication on Slack, or leverage Telegram for on-the-go updates, IFTTT’s versatile webhooks offer endless possibilities. By optimizing your digital environment with these integrations, you can ensure that you’re always in the know and can take timely actions, all while enjoying the ease of automation. So, if you’re seeking ways to link important emails with specific services, this tutorial will guide you through the process and empower you to tailor your digital experience to your unique needs