Create your own reminder application using AWS Lambda and Gmail.

Since everyone is so busy with their work people forget to keep tabs on their own health so, in order to take a small step towards a healthy lifestyle we can start off with the most basic habit. Drinking water regularly. In this article, we will see how we can create an application that notifies us to send emails every hour to remind us to drink water using Gmail and AWS Lambda which uses python language.

Since we have 1,000,000 free AWS Lambda requests from AWS every month, it’s free, why not use it to try and maintain your health?

Below we will see how to put everything together with AWS Lambda, AWS CloudWatch EventBridge, and Gmail.

 

Overview

We will begin by setting up your Gmail account so that you may send emails dynamically with Python.

For our purposes today, we’ll develop an AWS Lambda function for our email reminder and link it to a Lambda Trigger, in this case, CloudWatch Events. Next, we’ll create a CloudWatch Event Rule using cron to have our email reminder run at a set time every day.

Finally, we will complete the email reminder implementation. We will also give the entire implementation. From then on, you will be able to create your own custom reminder!

 

Step 1: Getting your credentials ready

First things first, you’ll need to generate an app password for your Gmail account for this tutorial.

You can check this document for help. https://support.google.com/mail/answer/185833?hl=en

We’ll need that in the following step!

 

Step 2: Let’s try sending an email!

To send emails, we’ll use the popular smtplib Python library; the package itself should be built into your Python interpreter. It will not need to be installed individually.

You may copy the following sample code, and modify the gmail_user, gmail_app_password, and sent_to variables before executing the script.

Note: For the gmail_app_password, is the app password that you have generated in Step 1 if you have 2FA enabled. Else, it will be your Gmail password.

import smtplib

gmail_user = “Your Email Here”

gmail_app_password = “Your Gmail App Password here”

sent_from = gmail_user

sent_to = [‘someone@gmail.com’, ‘anyone@gmail.com’]

sent_subject = ‘Test’

sent_body = ‘This is a test’

email_text = “””\

From: %s

To: %s

Subject: %s

%s

“”” % (sent_from, “, “.join(sent_to), sent_subject, sent_body)

try:

        server = smtplib.SMTP_SSL(‘smtp.gmail.com’, 465)

        server.ehlo()

        server.login(gmail_user, gmail_app_password)

        server.sendmail(sent_from, sent_to, email_text.encode(“utf-8”))

        server.close()

        print(email_text)

        print(‘Email sent!’)

    except Exception as exception:

        print(“Error: %s!\n\n” % exception)

 

Step 3: Creating your Lambda function on AWS

Once you’ve got the email sender operating, it’s time to set up Amazon Web Services. To begin, we will create a Lambda function on AWS Lambda.

 

What is AWS Lambda?

Image Source: Wikipedia

Amazon Web Services Lambda is an event-driven, serverless computing technology supplied by Amazon. It is a computer service that runs code in response to events and maintains the computing resources required by that code dynamically.

Note: we will be using python 3.7 for this application

Once you get your Lambda function created, you will see a lambda_function.py initialized with the lambda_handler as shown below.

import json

def lambda_handler(event, context):

    # TODO implement

    return {

        ‘statusCode’: 200,

        ‘body’: json.dumps(‘Hello from Lambda!’)

    }

The lambda_handler function will be invoked whenever the Lambda function is triggered. It acts similarly to the main function in a Python program. Hence, all your main program logic and function calls should be executed here.

Step 4: Associate your lambda function with a Lambda Trigger

Now you have your Lambda function ready, we now need to associate it with a CloudWatch EventBridge as a Lambda Trigger.

 For the use case, we will need the Lambda function to be executed every hour, hence we will be defining a cron expression that schedules the Lambda function to be executed accordingly.

 Go to the Lambda function, select your created function and click on add trigger. Click on the drop-down list and click on EventBridge.

Fill the form with appropriate names and descriptions and add your cron expression as shown below. You can check out this document to further understand how to modify cron expressions.

After you create the trigger your function will look something like this.

You can experiment with the cron expression and obtain a preview of the trigger date(s) while establishing the rule. Not to mention, set the target of the rule you made to the Lambda function you defined in Step 3, which is Test.

Note that in the source code above, we have a slightly different statement for the gmail_app_password which is below:

gmail_app_password = os.environ[‘MAIL_PASS’]

This is to prevent our credentials from appearing as plain text in the source code. We will treat it as an environment variable, where AWS will encrypt it for us.

Setting the MAIL_PASS environment variables for the Lambda function.

After getting everything done, save your function and you can test the function out! (If your function is time-dependent, you should hard code the time when testing it out, to make sure that it will send out emails normally ;))

The reminder is good to go!

Conclusion

This article has shown steps on how to set our Gmail accounts to be able to send emails programmatically with Python’s smtplib, create a Lambda function on AWS, configure an AWS CloudWatch Event Rule with a cron expression associating it with our Lambda function to trigger it accordingly as well as shared ways on securing your credentials with environment variables.

The Drinking water remainder that is mentioned above is just a mere example of how AWS Lambda together with AWS CloudWatch can be so useful in scheduling periodic tasks, especially for generating reminders.

You can easily develop your own Email Reminder with your own implementation and use case, you’ll only need the send_email from this example, and also the lambda_handler to start off with.