skip to Main Content

The code below to send an Amazon SES email works fine. However, I need the code to communicate with a local EC2 database, so I need to add this Lambda function to my VPC and Subnets – At this point, the code below stops working and timeouts.

How can I fix this?

import json
import boto3

def send_email_ses(email):
    client = boto3.client('ses', region_name='eu-west-1')
    
    try:
        response = client.send_email(
            Destination={
                'ToAddresses': [email]
            },
            Message={
                'Body': {
                    'Text': {
                        'Charset': 'UTF-8',
                        'Data': 'Hello world',
                    }
                },
                'Subject': {
                    'Charset': 'UTF-8',
                    'Data': 'Welcome! Your API Key',
                },
            },
            Source='[email protected]'
        )
        return response['MessageId']
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None

def lambda_handler(event, context):
    email = "[email protected]"
    message_id = send_email_ses(email)
    
    if message_id:
        body = f"Email Sent Successfully. MessageId is: {message_id}"
        status_code = 200
    else:
        body = "Failed to send email."
        status_code = 500

    return {
        'statusCode': status_code,
        'body': json.dumps(body)
    }`

Error Message:
Response { "errorMessage": "2024-06-26T05:12:37.998Z 34457ba1-910f-4f54-9ced-234dac1c0950 Task timed out after 5.01 seconds" }

If I remove the VPC, it works again.

2

Answers


  1. When an AWS Lambda function is connected to a VPC, it does not have Internet access by default. Therefore, the API call is hanging.

    The best way would be to create a VPC Endpoint for SES in your VPC. This will provide direct access to the Amazon SES endpoints without going via the Internet.

    See: Setting up VPC endpoints with Amazon SES – Amazon Simple Email Service

    Alternatively, you can place the Lambda function in a private subnet and launch a NAT Gateway in a public subnet. However, charges apply for the NAT Gateway, so the VPC Endpoint is a cheaper and easier option.

    Login or Signup to reply.
  2. When you add a Lambda function to a VPC and subnets, the Lambda function loses internet access unless the VPC has a NAT Gateway configured. This is because the subnets you attach your Lambda function to are likely private subnets without direct internet access. Amazon SES, which your Lambda function tries to communicate with, is an external service requiring internet access.
    To fix this issue, you need to ensure your Lambda function can access the internet from within your VPC. You can achieve this by setting up a NAT Gateway in your VPC.

    import json
    import boto3
    
    def send_email_ses(email):
    client = boto3.client('ses', region_name='eu-west-1')
    
    try:
        response = client.send_email(
            Destination={
                'ToAddresses': [email]
            },
            Message={
                'Body': {
                    'Text': {
                        'Charset': 'UTF-8',
                        'Data': 'Hello world',
                    }
                },
                'Subject': {
                    'Charset': 'UTF-8',
                    'Data': 'Welcome! Your API Key',
                },
            },
            Source='[email protected]'
        )
        return response['MessageId']
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None
    
    def lambda_handler(event, context):
    email = "[email protected]"
    message_id = send_email_ses(email)
    
    if message_id:
        body = f"Email Sent Successfully. MessageId is: {message_id}"
        status_code = 200
    else:
        body = "Failed to send email."
        status_code = 500
    
    return {
        'statusCode': status_code,
        'body': json.dumps(body)
    }
    

    Ensure your Lambda function has the necessary VPC configuration and your Lambda function’s IAM role has the necessary permissions to use SES and access the VPC

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search