minisch
minisch

Reputation: 343

Use AWS Lambda and SES to send an email

I ran the following script which works on my computer but doesnt work in AWS Lambda. All I did was added "def lambda_handler(event, context): return event" function as its required by the lambda. I ran the Lambda test a few times. I am not getting the SES email and there's no errors when I execute it in Lambda. Any idea why?

import boto3
from botocore.exceptions import ClientError


SENDER = "Sender Name <[email protected]>"
RECIPIENT = "[email protected]"
CONFIGURATION_SET = "ConfigSet"
AWS_REGION = "ap-southeast-2"
SUBJECT = "Amazon SES Test (SDK for Python)"
BODY_TEXT = ("Amazon SES Test (Python)\r\n"
             "This email was sent with Amazon SES using the "
             "AWS SDK for Python (Boto)."
            )
            

BODY_HTML = """<html>
</html>
            """            
def lambda_handler(event, context):
    return event
    
# The character encoding for the email.
CHARSET = "UTF-8"

# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)

try:
    response = client.send_email(
        Destination={
            'ToAddresses': [
                RECIPIENT,
            ],
        },
        Message={
            'Body': {
                'Html': {
                    'Charset': CHARSET,
                    'Data': BODY_HTML,
                },
                'Text': {
                    'Charset': CHARSET,
                    'Data': BODY_TEXT,
                },
            },
            'Subject': {
                'Charset': CHARSET,
                'Data': SUBJECT,
            },
        },
        Source=SENDER,
        ConfigurationSetName=CONFIGURATION_SET,
    )

except ClientError as e:
    print(e.response['Error']['Message'])
else:
    print(response['MessageId'])

Upvotes: 2

Views: 3472

Answers (1)

Allan Chua
Allan Chua

Reputation: 10175

Just like what Anon Coward said, you have to perform the SES sending inside the handler function and put the return statement at the bottom of that function.

It should look something like this:

def lambda_handler(event, context):
    response = client.send_email(PAYLOAD_HERE_)

    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "Region ": json_region
        })
    }

Upvotes: 1

Related Questions