Skip to main content

Amazon Web Services

Process Amazon Connect self-service data with Lambda and SES

In this blog post, we process data collected through a self-service Amazon Connect Contact flow and deliver results in an email. My previous article shows how to configure Amazon Connect and Amazon Lex to create a Self-service Contact Center experience.

Assuming the first part is done, it is time to process the data using a Lambda function. As the end result, I am sending out caller’s ticket data to a helpdesk email address, which auto-creates a ticket in our system. But why stop there? What I like the most about this ecosystem is the ability to add more building blocks as needed. Once we processed caller’s data with a Lambda the options are numerous – we can pipe that data further to a database, CRM, etc.


  • Create an Amazon Connect Contact flow and Lex Bot based on Self-service Contact Center with Amazon Connect and Amazon Lex
  • Prepare the stage for writing Python Lambdas
    • Install Python prerequisites (or use a language of your preference)
    • Make sure you have an IAM Role available for running Lambdas. If you have completed the steps from the previous blog post, you already have an IAM role that can be used here as well; we will only add new permissions as needed
  • Plan for at least two test email addresses


Simple Email Service (SES) configuration

Open the AWS Management Console and locate SES. This service provides an interface for sending and receiving emails. In this example, we use AWS SDK for Python to send emails from Lambda. In order to do so, it is necessary to perform all actions outlined in the Prerequisites section of this document.

Grant permissions for Lambda to use Simple Email Service resources (SES)

From IAM Management Console navigate to Policies. Create a new policy to grant permissions for sending emails using SES. To simplify this process, I suggest using the Policy Generator option and configuring the Policy as follows:

Click on Add Statement and proceed to the next step. Name the policy and create it.

Here is the full policy document:

    "Version": "2012-10-17",
    "Statement": [
            "Sid": "Stmt1510073458000",
            "Effect": "Allow",
            "Action": [
            "Resource": [
Amazon Web Services - Avoid Contact Center Outages: Plan Your Upgrade to Amazon Connect
Avoid Contact Center Outages: Plan Your Upgrade to Amazon Connect

Learn the six most common pitfalls when upgrading your contact center, and how Amazon Connect can help you avoid them.

Get the Guide

Navigate to Roles, then add the newly created Policy to your IAM role (the one used for running your Lambda function). To do that, click on Attach Policy button and add the AllowSesSendEmail policy.

**Tip: In case you’re wondering how I magically knew which permission will be required – I did not, I was able to find this info from Cloudwatch logs before my emails started successfully sending out. If your Lambda is failing to invoke another service due to insufficient permissions, there’s a good chance you will be able to find the details by inspecting the error message. To avoid permission errors, you could also grant a higher permission level during the testing phase.**

Create Lambda function

    1. From Lambda Management Console, click on Create function then select Author from scratch.
    2. Fill in the Basic information.
    3. Navigate to the Configuration tab, select Python 3.6 as your Runtime then paste the following code:
import logging
import boto3
from botocore.exceptions import ClientError
import os

logger = logging.getLogger()

def lambda_handler(event, context):

    logger.debug('Entering Lex data processing')
    logger.debug('Printing received event data')
    # Define constants
    SENDER = "Helpdesk Caller <>"
    RECIPIENT = ""
    AWS_REGION = "us-east-1"
    CHARSET = "UTF-8"

    # Parse data from Lex bot 
    ticketSubject = event['currentIntent']['slots']['SubjectLine']
    ticketText = event['currentIntent']['slots']['Text']
    ticketProductCategory = event['currentIntent']['slots']['TicketProduct']
    callerRegion = event['currentIntent']['slots']['City']
    openTicketConfirmationStatus = event['currentIntent']['confirmationStatus']
    logger.debug('Data picked up from lex ' + ticketSubject
   + ticketText + ticketProductCategory + callerRegion
   + openTicketConfirmationStatus)
    # Build e-mail content
    emailSubject = ticketSubject
    emailBody = """
        Hi Support,<br><br>
        A new ticket request has arrived in your queue.
        <p><b>Ticket category: </b>%s
        </p><p><b>Caller region: </b>%s
        </p><p><b>Ticket content: </b>%s
        </p><p>Please try to handle the request as soon as possible.
        </html>""" % (ticketProductCategory, callerRegion, ticketText)
    # Send email using SES resource
    sesClient = boto3.client('ses',region_name=AWS_REGION)
        response = sesClient.send_email(
            'ToAddresses': [
            'Body': {
                'Html': {
                    'Charset': CHARSET,
                    'Data': emailBody,
            'Subject': {
                'Charset': CHARSET,
                'Data': emailSubject,

# Display an error if something goes wrong.	
    except ClientError as e:
         print("Email sent! Message ID:"),
    # Return sucess to Amazon Connect IVR
            {"type": "Close",
            "fulfillmentState": "Fulfilled",
            "message": {
                "contentType": "PlainText",
                "content": "Your ticket data has been saved."

You will need to modify the following variables to match your environment: SENDER, RECIPIENT, AWS_REGION.

Here is a sample test event to verify your Lambda is working well:

  "currentIntent": {
    "dialogState": "ReadyForFulfillment",
    "intentName": "CollectTicketProperties",
    "message": null,
    "responseCard": null,
    "slotToElicit": null,
    "slots": {
      "City": "Boston",
      "SubjectLine": "Not able to use the webchat",
      "Text": "I can't reach the client webchat please assist",
      "TicketProduct": "Webchat"
    "confirmationStatus": "confirmed"

Note: this Lambda example was created based on the following AWS guidance: Send an Email using the AWS SDK for Python.

Once you have determined the Lambda is working well, it’s time to put all pieces together.

Fulfill Lex bot intent with newly created Lambda function

Navigate to the Lex Management Console, edit your self-service ticketing bot and select your Lambda function from the Fulfilment section.

Save the Intent, then Build and Publish your Lex bot.

We configured the Amazon Connect part in the previous post, so that’s it! Simply dial into your Amazon Connect Service Desk and speak about your issue. It should result in an email similar to the following:

If you’re interested to see more, schedule a demo or contact us here.

Thoughts on “Process Amazon Connect self-service data with Lambda and SES”

  1. Hi Dora,

    Excellent work however I am confused by what these lines of code are meant to do as it’s causing an error when I test the function

    emailBody = “””
    “”” % (ticketProductCategory, callerRegion, ticketText)



  2. Dora Hodanic Post author

    Hi Boyd, thank you for reaching out. I apologize, unfortunately, it seems the emailBody variable did not format well after it was pasted from a Lambda. I corrected this part within the article and added the sample to the following GitHub repository:

    The purpose of this code part is to build out the HTML body of the e-mail message by inserting the data collected from Amazon Lex input event.
    Please feel free to let me know if you run into further problems.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Dora Hodanic

Lead Technical consultant focused on contact center solutions with Amazon Connect.

More from this Author

Follow Us