Python-bloggers

Automate Weather Email Alerts Using AWS Lambda, EventBridge & SES

This article was first published on Technical Posts – The Data Scientist , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

A beginner-friendly project introducing AWS Lambda & EventBridge notification service

Karan Gupta

Sep 6, 2025

Introduction

From Babylonians using cloud patterns in 650 BC to predict weather to getting a notification on your phone [1], humans have come a long way towards predicting weather patterns. AI models for weather prediction have evolved like Google’s GenCast [2] which are expected to produce forecasts with better accuracy than traditional systems. Along with accurate prediction, the timing for notification is crucial as it impacts day to day lives.

Today, sending a custom weather alert is surprisingly simple, thanks to open weather APIs and AWS services like Lambda and EventBridge.

How does the email notification work: We are going to make an API call to Openweathermap.org (an open-source weather database) via an AWS Lambda function. AWS EventBridge is going to ask the Lambda function to make this call on a schedule.

Let’s look at the steps:

Step 1: Prerequisites

Step 2: Create IAM role for Lambda Function

Step 3: Create the Lambda Function

Step 4: Create Schedule in EventBridge

Step 5: Test the function

Step 1: Completing the Pre-requisites

First, we need an AWS account. You can create a free account using the following link

Next, we are going to use AWS Simple Email Service to create two emails, one to send email and other to receive the notification.

Next, go to https://home.openweathermap.org/api_keys and generate your API key

Step 2: Create IAM role for Lambda function

Identity and Access Management roles provide necessary permissions for AWS resources to interact with each other.

Go to IAM inside your AWS Account and do the following:

Image: AWS IAM Roles

 Step 3: Create Lambda Function

Lambda is AWS compute service that scales automatically without managing servers. User just run their code, Lambda manages other resources like memory, CPU, network as needed [3].

In this step, we are going to create the Lambda Function, and do the following

Image: AWS Lambda Environment variables

Next, we are going to add the following code to the Lambda function. In this function, we import the necessary packages and set the environment variables. Then, we create a function which is going to make an API call to OpenWeather using the API key. Finally, we are creating an email body to be sent out with the weather information

import boto3
import urllib.request
import json
import os
from botocore.exceptions import ClientError


# Get env vars which are stored on the Lambda Environment 
OPENWEATHER_API_KEY = os.environ['OPENWEATHER_API_KEY']
CITY = os.environ.get('CITY')
EMAIL_FROM = os.environ['EMAIL_FROM']
EMAIL_TO = os.environ['EMAIL_TO']


def lambda_handler(event, context):
    # Fetch weather from OpenWeatherMap using urllib library and the API key from OpenWeatherMap
    url = f"http://api.openweathermap.org/data/2.5/weather?q=New%20York&appid={OPENWEATHER_API_KEY}&units=metric"


    try:
        with urllib.request.urlopen(url) as response:
            data = json.loads(response.read().decode())
    except Exception as e:
        print("Error fetching weather:", str(e))
        return {"status": "failed", "error": str(e)}


    if "main" not in data:
        print("Error in API response:", data)
        return {"status": "failed", "error": data}


    temp = data['main']['temp']
    humidity = data['main']['humidity']
    condition = data['weather'][0]['description'].title()


    subject = f"🌤 Daily Weather Report – {CITY}"
    body = f"""
    Daily Weather Report – {CITY}


    Temperature: {temp}°C
    Humidity: {humidity}%
    Condition: {condition}


    Have a great day!
    """


    # Send email via SES
    ses = boto3.client('ses', region_name="us-east-1")
    try:
        ses.send_email(
            Source=EMAIL_FROM,
            Destination={"ToAddresses": [EMAIL_TO]},
            Message={
                "Subject": {"Data": subject},
                "Body": {"Text": {"Data": body}}
            }
        )
        print("Email sent successfully")
        return {"status": "success"}
    except ClientError as e:
        print("SES Error:", e)
        return {"status": "failed", "error": str(e)}

Image: AWS Lambda Function Code

Click deploy and test your function

Note: If you encounter import errors for the requests library, consider using urllib.request, which is built-in and works well for this use case.

Step 4: Create EventBridge Schedule

In this step, we are going to create a schedule for this function to start and send the notification. Go to the EventBridge console in AWS and follow these steps

              Image: EventBridge Schedule

Step 5: Testing the function

Although the Lambda function would trigger at the scheduled time, there are cloudshell commands that we can use to trigger the function to test its functionality right away.

To do that, open cloudshell from the top of the AWS console. Once it’s open, type in the following code and replace the function name with your Lambda function name.

aws lambda invoke 
  --function-name YourLambdaName 
  --payload '{}' 
  response.json

Image: AWS CloudShell

You should see the following output. Status Code 200 means that the function ran successfully.

      Image: AWS CloudShell

The email did come to my inbox, but it landed in the spam box as you can see below

Image: Gmail

Conclusion

With the use of Open Weather API, AWS Lambda and EventBridge, we have successfully created an email alert system in AWS. We can continue building more advanced alert system based on the same process. A possible advanced method is to aggregate data from multiple weather forecasts and standardize is to get more accurate alerts.

If you have any questions or suggestions, please reach out to me.

References

[1]https://en.wikipedia.org/wiki/Weather_forecasting

[2] https://deepmind.google/discover/blog/gencast-predicts-weather-and-the-risks-of-extreme-conditions-with-sota-accuracy/

[3]https://docs.aws.amazon.com/lambda/latest/dg/welcome.html

 Karan Gupta

Karan Gupta is a seasoned Data Engineer with over a decade of experience spanning consulting and asset management.His expertise lies in designing scalable data pipelines and ensuring reliable data-driven solutions that empower business decision-making.

Outside of work, Karan enjoys reading, writing, and keeping pace with emerging trends in data engineering and computer science. He is particularly enthusiastic about exploring how new tools and frameworks can enhance data processing and analytics in real-world applications.

Karan is also committed to helping aspiring professionals, offering career advice and interview preparation guidance. Connect with him on LinkedIn

To leave a comment for the author, please follow the link and comment on their blog: Technical Posts – The Data Scientist .

Want to share your content on python-bloggers? click here.
Exit mobile version