> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sendpost.io/llms.txt
> Use this file to discover all available pages before exploring further.

# AWS Lambda Quickstart

> Learn how to send emails with SendPost in AWS Lambda functions using Node.js, Python, and other runtimes

## Prerequisites

To get the most out of this guide, you'll need to:

* [**Create a SendPost Account**](https://app.sendpost.io/register)
* [**AWS Account**](https://aws.amazon.com/) with Lambda access
* A **Sub-Account API Key** from your SendPost dashboard

<Info>
  You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails.
</Info>

## 1. Node.js Lambda Function

### Install Dependencies

Create a `package.json` file:

```json JSON theme={null}
{
  "name": "sendpost-lambda",
  "version": "1.0.0",
  "dependencies": {
    "sendpost-js-sdk": "^1.0.0"
  }
}
```

Install dependencies:

```shellscript npm theme={null}
npm install
```

### Basic Lambda Function

Create `index.js`:

```javascript JavaScript theme={null}
const sendpost = require('sendpost-js-sdk');

const emailApi = new sendpost.EmailApi();
const API_KEY = process.env.SENDPOST_API_KEY;

exports.handler = async (event) => {
  try {
    const { to, subject, htmlBody, textBody } = JSON.parse(event.body || event);
    
    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{ email: to }];
    emailMessage.subject = subject;
    emailMessage.htmlBody = htmlBody;
    emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, '');
    emailMessage.trackOpens = true;
    emailMessage.trackClicks = true;

    const response = await emailApi.sendEmail(API_KEY, { emailMessage });

    return {
      statusCode: 200,
      body: JSON.stringify({
        success: true,
        messageId: response.messageId
      })
    };
  } catch (error) {
    console.error('SendPost error:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({
        success: false,
        error: error.message
      })
    };
  }
};
```

### Environment Variables

In AWS Lambda Console, add environment variables:

* `SENDPOST_API_KEY`: your\_sub\_account\_api\_key

### Deploy with AWS CLI

```bash theme={null}
zip -r function.zip index.js node_modules package.json
aws lambda update-function-code \
  --function-name sendpost-email \
  --zip-file fileb://function.zip
```

## 2. Python Lambda Function

### Install Dependencies

Create `requirements.txt`:

```txt theme={null}
sendpost-python-sdk
```

### Basic Lambda Function

Create `lambda_function.py`:

```python Python theme={null}
import json
import os
import sendpost_python_sdk
from sendpost_python_sdk.api import EmailApi
from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient

def lambda_handler(event, context):
    try:
        # Parse request body
        if isinstance(event.get('body'), str):
            body = json.loads(event['body'])
        else:
            body = event
        
        to = body.get('to')
        subject = body.get('subject')
        html_body = body.get('htmlBody')
        text_body = body.get('textBody')
        
        # Configure SendPost
        configuration = sendpost_python_sdk.Configuration(
            host="https://api.sendpost.io/api/v1"
        )
        configuration.api_key['subAccountAuth'] = os.environ['SENDPOST_API_KEY']
        
        with sendpost_python_sdk.ApiClient(configuration) as api_client:
            email_message = EmailMessageObject()
            email_message.var_from = EmailAddress(
                email='hello@playwithsendpost.io',
                name='SendPost'
            )
            email_message.to = [Recipient(email=to)]
            email_message.subject = subject
            email_message.html_body = html_body
            email_message.text_body = text_body or html_body.replace(r'<[^>]+>', '')
            email_message.track_opens = True
            email_message.track_clicks = True
            
            response = EmailApi(api_client).send_email(email_message)[0]
            
            return {
                'statusCode': 200,
                'body': json.dumps({
                    'success': True,
                    'messageId': response.message_id
                })
            }
    except Exception as e:
        print(f'SendPost error: {str(e)}')
        return {
            'statusCode': 500,
            'body': json.dumps({
                'success': False,
                'error': str(e)
            })
        }
```

### Deploy with AWS CLI

```bash theme={null}
pip install -r requirements.txt -t .
zip -r function.zip lambda_function.py sendpost_python_sdk
aws lambda update-function-code \
  --function-name sendpost-email-python \
  --zip-file fileb://function.zip
```

## 3. Common Use Cases

### Welcome Email Lambda

**Node.js version:**

```javascript JavaScript theme={null}
exports.handler = async (event) => {
  try {
    const { email, firstName } = JSON.parse(event.body);
    
    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{
      email,
      name: firstName,
      customFields: { firstName }
    }];
    emailMessage.subject = 'Welcome {{firstName}}!';
    emailMessage.htmlBody = `
      <h1>Welcome, {{firstName}}!</h1>
      <p>Thank you for joining us. We're excited to have you on board.</p>
      <p><a href="{{unsubscribe}}">Unsubscribe</a></p>
    `;
    emailMessage.groups = ['welcome'];

    const response = await emailApi.sendEmail(API_KEY, { emailMessage });

    return {
      statusCode: 200,
      body: JSON.stringify({
        success: true,
        messageId: response.messageId
      })
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ success: false, error: error.message })
    };
  }
};
```

### Password Reset Email Lambda

**Python version:**

```python Python theme={null}
def lambda_handler(event, context):
    try:
        body = json.loads(event['body']) if isinstance(event.get('body'), str) else event
        email = body['email']
        reset_token = body['resetToken']
        first_name = body.get('firstName', 'User')
        app_url = os.environ.get('APP_URL', 'https://yourapp.com')
        reset_url = f"{app_url}/reset-password?token={reset_token}"
        
        configuration = sendpost_python_sdk.Configuration(
            host="https://api.sendpost.io/api/v1"
        )
        configuration.api_key['subAccountAuth'] = os.environ['SENDPOST_API_KEY']
        
        with sendpost_python_sdk.ApiClient(configuration) as api_client:
            email_message = EmailMessageObject()
            email_message.var_from = EmailAddress(
                email='hello@playwithsendpost.io',
                name='SendPost'
            )
            email_message.to = [Recipient(
                email=email,
                name=first_name,
                custom_fields={
                    'firstName': first_name,
                    'resetUrl': reset_url
                }
            )]
            email_message.subject = 'Reset Your Password'
            email_message.html_body = f'''
                <h2>Hello {{firstName}},</h2>
                <p>Click the link below to reset your password:</p>
                <p><a href="{{resetUrl}}">Reset Password</a></p>
                <p>This link expires in 1 hour.</p>
            '''
            email_message.groups = ['password-reset']
            
            response = EmailApi(api_client).send_email(email_message)[0]
            
            return {
                'statusCode': 200,
                'body': json.dumps({
                    'success': True,
                    'messageId': response.message_id
                })
            }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'success': False, 'error': str(e)})
        }
```

## 4. API Gateway Integration

### Create API Gateway Endpoint

1. Create a new API Gateway REST API
2. Create a POST method
3. Set integration type to Lambda Function
4. Select your Lambda function
5. Deploy to a stage

### Example Request

```bash theme={null}
curl -X POST https://your-api-id.execute-api.region.amazonaws.com/stage/send-email \
  -H "Content-Type: application/json" \
  -d '{
    "to": "user@example.com",
    "subject": "Hello from Lambda",
    "htmlBody": "<h1>Hello!</h1><p>This email was sent from AWS Lambda.</p>"
  }'
```

## 5. Using Lambda Layers (Node.js)

### Create Layer

```bash theme={null}
mkdir -p nodejs/node_modules
npm install sendpost-js-sdk --prefix nodejs/
zip -r sendpost-layer.zip nodejs/
aws lambda publish-layer-version \
  --layer-name sendpost-sdk \
  --zip-file fileb://sendpost-layer.zip \
  --compatible-runtimes nodejs18.x nodejs20.x
```

### Use Layer in Lambda

Attach the layer to your Lambda function in the AWS Console or via CLI:

```bash theme={null}
aws lambda update-function-configuration \
  --function-name sendpost-email \
  --layers arn:aws:lambda:region:account:layer:sendpost-sdk:1
```

## 6. Error Handling & Logging

### Enhanced Error Handling

```javascript JavaScript theme={null}
exports.handler = async (event) => {
  const requestId = event.requestContext?.requestId || 'unknown';
  
  try {
    // Validate input
    if (!event.body) {
      throw new Error('Request body is required');
    }
    
    const body = JSON.parse(event.body);
    if (!body.to || !body.subject || !body.htmlBody) {
      throw new Error('Missing required fields: to, subject, htmlBody');
    }
    
    // Send email
    const response = await emailApi.sendEmail(API_KEY, { emailMessage });
    
    console.log(`Email sent successfully: ${response.messageId}`, {
      requestId,
      to: body.to
    });
    
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'X-Request-Id': requestId
      },
      body: JSON.stringify({
        success: true,
        messageId: response.messageId,
        requestId
      })
    };
  } catch (error) {
    console.error('Lambda error:', {
      requestId,
      error: error.message,
      stack: error.stack
    });
    
    return {
      statusCode: error.message.includes('required') ? 400 : 500,
      headers: {
        'Content-Type': 'application/json',
        'X-Request-Id': requestId
      },
      body: JSON.stringify({
        success: false,
        error: error.message,
        requestId
      })
    };
  }
};
```

## 7. Testing Locally

### Using SAM CLI

Create `template.yaml`:

```yaml theme={null}
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  SendPostEmailFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs20.x
      Environment:
        Variables:
          SENDPOST_API_KEY: your_api_key
      Events:
        SendEmail:
          Type: Api
          Properties:
            Path: /send-email
            Method: post
```

Test locally:

```bash theme={null}
sam local start-api
```

### Using Lambda Runtime Interface Emulator

```bash theme={null}
docker run -p 9000:8080 \
  -e SENDPOST_API_KEY=your_api_key \
  -v "$PWD":/var/task \
  public.ecr.aws/lambda/nodejs:20
```

Test:

```bash theme={null}
curl -X POST "http://localhost:9000/2015-03-31/functions/function/invocations" \
  -d '{"body": "{\"to\":\"user@example.com\",\"subject\":\"Test\",\"htmlBody\":\"<h1>Test</h1>\"}"}'
```

<Warning>
  Make sure your sender email domain is verified in your SendPost account before sending emails.
</Warning>

## 8. Next Steps

Explore more examples and use cases:

<Columns cols={3}>
  <Card title="AWS Lambda Documentation" icon="aws" href="https://docs.aws.amazon.com/lambda/">
    Learn more about AWS Lambda
  </Card>

  <Card title="SendPost JavaScript SDK" icon="npm" href="https://www.npmjs.com/package/sendpost-js-sdk">
    View the official SDK package on npm
  </Card>

  <Card title="SendPost Python SDK" icon="python" href="https://pypi.org/project/sendpost-python-sdk/">
    View the official SDK package on PyPI
  </Card>
</Columns>

<Columns cols={3}>
  <Card title="Quickstart Example" icon="github" href="https://github.com/sendpost/sendpost-aws-lambda-example">
    Complete working example from this quickstart guide
  </Card>
</Columns>
