How do I use Lambda and Amazon SES to send email?

5 minute read
2

I want to use AWS Lambda and Amazon Simple Email Service (Amazon SES) to send emails.

Short description

To send email from a Lambda function using Amazon SES, complete these steps:

1.    Create an AWS Identity and Access Management (IAM) policy and execution role for Lambda to run the API call.

2.    Verify your Amazon SES identity (domain or email address).

3.    Create or update a Lambda function that includes logic for sending email through Amazon SES.

Note: To include a PDF attachment in your emails, you must use the Amazon SES SendRawEmail API operation. For more information, see Sending raw email using the Amazon SES API on GitHub.

Resolution

Note: The Node.js, Python, and Ruby Lambda function code examples in this article requires modification depending on your use case. Adapt the example to your use case, or design your own in your preferred programming language.

Create an IAM policy and execution role for Lambda to run the API call

1.    Create an IAM policy using the JSON policy editor. When you create the policy, paste the following JSON policy document into the policy editor:

{
 "Version": "2012-10-17",
 "Statement": [
 {
 "Effect": "Allow",
 "Action": [
 "ses:SendEmail",
 "ses:SendRawEmail"
 ],
 "Resource": "*"
 }
 ]
}

Note: For more information and examples of how to restrict access to this policy, see Example IAM policies for Amazon SES.

2.    Attach the IAM policy to an IAM role. For instructions, see the To use a managed policy as a permissions policy for an identity (console) section in Adding IAM identity permissions (console).

Note: You'll assign this IAM role to your Lambda function in the following steps.

Verify your Amazon SES identity (domain or email address)

To verify a domain, see Verifying a DKIM domain identity with your DNS provider.

To verify an email address, see Verifying an email address identity.

Create or update a Lambda function that includes logic for sending email through Amazon SES

1.    If you haven't done so already, create a Lambda function.

Note: You can create a Lambda function by using the Lambda console or by building and uploading a deployment package.

2.    In the Lambda console, in the left navigation pane, choose Functions.

3.    Choose the name of your function.

4.    On the Configuration tab, in the Permissions pane, look at the function's Execution Role. Verify that the IAM role with Amazon SES permissions that you created earlier is listed. If the correct IAM role isn't listed, then assign the correct role to the function.

5.    Under Function code, in the editor pane, paste one of the following function code examples. Be sure to use the relevant example for your runtime and version of Node.js, Python, or Ruby.

Important: Replace us-west-2 with the AWS Region that your verified Amazon SES identity is in. Replace "RecipientEmailAddress", ... with the email address or addresses that you want to send the email to. Replace SourceEmailAddress with your Amazon SES-verified sender email address, or any email address from an Amazon SES-verified domain. Optionally, edit the message body ("Test") and subject line ("Test Email").

For Node.js versions 18 and newer, see the following example code:

// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";
const ses = new SESClient({ region: "us-west-2" });

export const handler = async(event) => {
  const command = new SendEmailCommand({
    Destination: {
      ToAddresses: ["RecipientEmailAddress", ...],
    },
    Message: {
      Body: {
        Text: { Data: "Test" },
      },

      Subject: { Data: "Test Email" },
    },
    Source: "SourceEmailAddress",
  });

  try {
    let response = await ses.send(command);
    // process data.
    return response;
  }
  catch (error) {
    // error handling.
  }
  finally {
    // finally.
  }
};

For Node.js versions 16 and older, see the following example code::

// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

var aws = require("aws-sdk");
var ses = new aws.SES({ region: "us-west-2" });
exports.handler = async function (event) {
  var params = {
    Destination: {
      ToAddresses: ["RecipientEmailAddress", ...],
    },
    Message: {
      Body: {
        Text: { Data: "Test" },
      },

      Subject: { Data: "Test Email" },
    },
    Source: "SourceEmailAddress",
  };
 
  return ses.sendEmail(params).promise()
};

For Python version 3.9, see the following example code:

import json
import boto3

client = boto3.client('ses', region_name='us-west-2')

def lambda_handler(event, context):
    
    response = client.send_email(
    Destination={
        'ToAddresses': ['RecipientEmailAddress']
    },
    Message={
        'Body': {
            'Text': {
                'Charset': 'UTF-8',
                'Data': 'This is the message body in text format.',
            }
        },
        'Subject': {
            'Charset': 'UTF-8',
            'Data': 'Test email',
        },
    },
    Source='SourceEmailAddress'
    )
    
    print(response)
    
    return {
        'statusCode': 200,
        'body': json.dumps("Email Sent Successfully. MessageId is: " + response['MessageId'])
    }

For Ruby version 2.7, see the following example code:

require "aws-sdk-ses"

$ses = Aws::SES::Client.new(region: "us-west-2")

def lambda_handler(event:, context:)
  
  resp = $ses.send_email({
  destination: {
    to_addresses: ["RecipientEmailAddress"], 
  }, 
  message: {
    body: {
      text: {
        charset: "UTF-8", 
        data: "This is the message body in text format.", 
      }, 
    }, 
    subject: {
      charset: "UTF-8", 
      data: "Test email", 
    }, 
  },
  source: "SourceEmailAddress"
})
    { statusCode: 200, body: JSON.generate("Message Sent Successfully. #{resp.to_h} ") }
end

For more information about using the sendEmail API, see the AWS SDK documentation for JavaScript, Python, Ruby, and Java V2.

6.    Choose Deploy.

(Optional) Send a test email

1.    In the Lambda console, configure a test event for your function.

Note: The test payload is required but isn't used for this code example.

2.    Choose Test. Lambda uses Amazon SES to send the test email to your recipient.

Related information

Sending email using Amazon SES

Identity and access management in Amazon SES

AWS OFFICIAL
AWS OFFICIALUpdated a year ago