Sending an email with AWS Lambda Function (Python)

Ivhani Maselesele
3 min readApr 20, 2020

In this section we talk about writing python code to send an email. Luckily this bloke wrote an article about automating an email to his girlfriend (smart dude); I’m pretty sure that landed him in trouble. Most of the code presented here is credited to Xzk Khooi, see his medium article here: https://medium.com/@xzkkhooi/how-i-deployed-an-email-reminder-for-my-girlfriend-with-aws-lambda-for-free-9173fb0433a7. At this point, we have the following assumptions:

  • You have basic Python programming skills
  • You have installed Python and pip on your machine

Before talking about the code used, here are some of the things I learnt:

  • “Lambda counts a request each time it starts executing in response to an event notification or invoke call, including test invokes from the console.”, so write and test your code on your machine.
  • Sending emails might work on your local machine and might not work on AWS EC2 instances, see reason in the next point.
  • According to this Stackoverflow answer, “Because of the spam abuse that has historically been sent from people using EC2 instances, virtually ALL popular mail providers block the receipt of email from EC2 instances.” — Ryan Parman
  • “AWS offers Amazon Simple Email Service that once can use to send. AWS works with mail providers to ensure that the nodes used by SES have been whitelisted because we do proper authorization/verification up-front.” — Ryan Parman
  • Depending on what you are trying to do, you might be able to send emails with SES for free, see pricing for US East region below, latest pricing here.
AWS SES Pricing
  • So this solution will mainly work for people that are not using Gmail or any other popular mail provider. I tested this with a Webmail hosted mail server.

Now back to the python code I used. I basically only extracted the parts I needed from this article, see code below:

Simple Python script to send email

Once I was able send an email in Python, I had to go create an AWS Lambda function and run test this code. See instructions below:

  • Log into AWS console
  • Go to service and select the AWS Lambda service
  • Click create a function
  • Give it a name and chose Python as the runtime environment
  • Click create function and it should take you to the designer.
  • In the designer, click the Lambda, paste the send_email() python code below the lambda_handler function.
  • Call the send email function inside the lambda_handler function.
  • Don’t forget the imports when copying your code across.
  • There should be a test button on the top right of your page, use this to test your function.
  • Remember that Amazon will probably charge you for these requests.

Congratulations, you’ve created your first Lambda.

In the next section, we’ll set up a trigger. Click here to go to the next section.

This is tutorial is broken up into 5 parts:

--

--