This example demonstrates how to use the Nylas SDK in an AWS Lambda function to send email attachments. It provides a simple web interface for uploading multiple files and sending them as email attachments.
This example serves two main purposes:
- Demonstrate Nylas SDK usage in AWS Lambda - Shows how to integrate the Nylas SDK in a serverless AWS Lambda environment
- Prove bug fix - Demonstrates that the previously reported bug ("Node.js SDK v7.9.0-7.13.3: Lambda freezes when sending emails with 2+ attachments over 3MB total") has been fixed
- Simple Web UI: Drag & drop or click to upload multiple files
- Multiple File Support: Test sending 2+ attachments simultaneously
- Size Tracking: Visual indicator when total attachment size exceeds 3MB
- Automatic Encoding: SDK automatically switches between JSON and multipart/form-data based on payload size
- Real-time Feedback: Loading states and success/error messages
- Serverless: Runs on AWS Lambda with API Gateway
Before getting started, you'll need:
- Nylas Account: Sign up for free
- AWS Account: Sign up for free
- Node.js: Version 16 or higher
- Nylas Application: Created in your Nylas Dashboard
- Connected Email Account: At least one email account connected to your Nylas application
- AWS CLI: Install AWS CLI (optional, but recommended)
- Serverless Framework: Will be installed via npm
The easiest way to get started is using the interactive setup CLI:
# Navigate to the aws-lambda directory
cd examples/aws-lambda
# Run the interactive setup
npm run setupThis will:
- Check prerequisites (Node.js, npm, AWS CLI, Serverless Framework)
- Guide you through Nylas credentials setup
- Help configure AWS credentials
- Create
.envfile with your configuration - Optionally deploy to AWS Lambda immediately
cd examples/aws-lambda
npm installCreate a .env file in the aws-lambda directory:
NYLAS_API_KEY=your_nylas_api_key_here
NYLAS_API_URI=https://api.us.nylas.com
NYLAS_GRANT_ID=your_grant_id_hereHow to get these values:
- NYLAS_API_KEY: Found in your Nylas Dashboard under your application settings
- NYLAS_GRANT_ID: The ID of a connected email account (found in Dashboard > Grants)
- NYLAS_API_URI: Use
https://api.us.nylas.comfor US region, or your specific region's API URL
Set up AWS credentials using one of these methods:
Option A: AWS CLI (Recommended)
aws configureOption B: Environment Variables
export AWS_ACCESS_KEY_ID=your_access_key
export AWS_SECRET_ACCESS_KEY=your_secret_key
export AWS_REGION=us-east-1Option C: AWS Credentials File
Create ~/.aws/credentials:
[default]
aws_access_key_id = your_access_key
aws_secret_access_key = your_secret_keynpm run deployThis will:
- Build your Lambda function using esbuild
- Upload it to AWS Lambda
- Create an API Gateway endpoint
- Display your function URL
- Visit the API Gateway URL displayed after deployment
- Fill in the email form:
- Recipient Email: Enter a valid email address
- Subject: Enter an email subject
- Message: Enter your message content
- Attachments: Upload multiple files (try files totaling over 3MB to test the bug fix)
- Click "Send Email with Attachments"
- Check the recipient's inbox for the email
User Browser → API Gateway → AWS Lambda → Nylas API → Email Provider
- File Upload: User uploads files through the web interface
- API Gateway: Receives HTTP request and forwards to Lambda
- Lambda Handler: Processes multipart form data and prepares attachments
- Nylas SDK: Automatically handles encoding based on payload size
- Email Sending: Nylas SDK sends email with attachments
- Response: User receives confirmation or error message
The SDK automatically handles large attachments by switching encoding methods:
- < 3MB total: Uses JSON encoding (faster, simpler)
- ≥ 3MB total: Uses multipart/form-data encoding (handles large files)
This prevents Lambda from freezing when sending multiple attachments over 3MB total. The web interface shows a warning indicator when the total size exceeds 3MB.
Lambda Handler (src/handler.ts):
- Handles API Gateway events
- Parses multipart form data from API Gateway (basic implementation)
- Uses Buffer attachments (optimal for Lambda)
- Automatically leverages SDK's 3MB threshold handling
Note on Multipart Parsing: The example includes a basic multipart parser for simplicity. For production use with large files or complex requirements, consider using a library like lambda-multipart-parser or busboy for more robust parsing.
SDK Integration:
// The SDK automatically chooses encoding based on total payload size
const response = await nylas.messages.send({
identifier: env.NYLAS_GRANT_ID,
requestBody: sendRequest,
});The SDK checks calculateTotalPayloadSize() internally and switches to multipart/form-data when needed (see src/resources/messages.ts in the SDK).
Key configuration options:
- Memory: 512MB (adjustable for larger files)
- Timeout: 30 seconds (increase for very large attachments)
- Runtime: Node.js 20.x
- Region: us-east-1 (changeable)
To modify these settings, edit serverless.yml:
provider:
memorySize: 1024 # Increase for larger files
timeout: 60 # Increase timeout
region: eu-west-1 # Change regionYou can also set environment variables in serverless.yml:
provider:
environment:
NYLAS_API_KEY: ${env:NYLAS_API_KEY}
NYLAS_API_URI: ${env:NYLAS_API_URI}
NYLAS_GRANT_ID: ${env:NYLAS_GRANT_ID}Or use AWS Systems Manager Parameter Store:
provider:
environment:
NYLAS_API_KEY: ${ssm:/nylas/api-key}
NYLAS_GRANT_ID: ${ssm:/nylas/grant-id}Error: "Missing required environment variables"
- Ensure
.envfile exists with all required variables - Check that variables are set correctly (no extra spaces)
- For production, ensure environment variables are set in AWS Lambda console
Error: "AWS credentials not configured"
- Run
aws configureto set up credentials - Or set
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYenvironment variables - Or create
~/.aws/credentialsfile manually
Error: "Serverless Framework not found"
- Run
npm installto install dependencies - Use
npx serverlessinstead ofserverlessif not installed globally
Error: "Lambda timeout"
- Increase timeout in
serverless.yml(default: 30 seconds) - For very large files, consider increasing memory as well
Error: "File upload fails"
- Check API Gateway payload size limits (10MB default)
- Ensure multipart/form-data is being sent correctly
- Check Lambda logs:
npm run logs
Email not received
- Verify the recipient email address
- Check spam/junk folders
- Verify your Nylas grant has send permissions
- Check Nylas Dashboard for any API errors
Lambda freezes with large attachments
- This bug was fixed in SDK v7.13.4+
- Ensure you're using the latest SDK version
- The SDK automatically uses multipart/form-data for payloads ≥ 3MB
Error: "Cannot find module 'index'"
- This usually means the handler setting is incorrect
- Verify the handler is set to exactly:
handler.handler(notindex.handlerorhandler) - The handler format is:
filename.functionName - For this example: file is
handler.js, function ishandler, so handler =handler.handler - Check Lambda Configuration → Runtime settings → Handler
- Rebuild and re-upload the zip file if you changed the handler code
View Lambda logs in real-time:
npm run logsOr check logs in AWS Console:
- Go to AWS Lambda Console
- Select your function
- Click "Monitor" tab
- View CloudWatch Logs
Add logging to the handler for debugging:
console.log('File details:', {
count: files.length,
totalSize: totalSize,
files: files.map(f => ({ name: f.filename, size: f.size }))
});- Cloudflare Workers: See
../edge-environment/for a Cloudflare Workers example - Local Attachment Examples: See
../messages/examples/for Node.js examples - Nylas SDK Documentation: https://developer.nylas.com
- AWS Lambda Docs: https://docs.aws.amazon.com/lambda/
- Serverless Framework Docs: https://www.serverless.com/framework/docs
If you prefer to upload the Lambda function manually through the AWS Console instead of using Serverless Framework:
npm run build:manualThis will:
- Install production dependencies
- Bundle your code with esbuild
- Create a
lambda-package.zipfile ready for upload
-
Go to AWS Lambda Console
- Navigate to AWS Lambda Console
- Select your region (e.g., us-west-1)
-
Create or Select a Function
- Click "Create function" or select an existing function
- Choose "Author from scratch"
- Function name:
nylas-attachment-sender(or your preferred name) - Runtime: Node.js 20.x
- Architecture: x86_64
-
Upload the Package
- In the function's "Code" tab, click "Upload from" → ".zip file"
- Select the
lambda-package.zipfile created in step 1 - Click "Save"
-
Configure the Handler
- In the "Runtime settings" section, click "Edit"
- Set Handler to:
handler.handler - Click "Save"
-
Set Environment Variables
- Go to the "Configuration" tab → "Environment variables"
- Click "Edit" → "Add environment variable"
- Add the following:
NYLAS_API_KEY: Your Nylas API keyNYLAS_GRANT_ID: Your Nylas Grant IDNYLAS_API_URI:https://api.us.nylas.com(or your region's API URI)
- Click "Save"
-
Configure Function Settings
- Go to "Configuration" → "General configuration" → "Edit"
- Memory: 512 MB (or higher for larger files)
- Timeout: 30 seconds (or higher for larger files)
- Click "Save"
-
Create API Gateway HTTP API
- Go to API Gateway Console
- Click "Create API" → "HTTP API" → "Build"
- Click "Add integration"
- Integration type: Lambda
- Lambda function: Select your function name
- API name:
nylas-attachment-api(or your preferred name) - Click "Next" → "Create"
-
Configure Routes
- In your API, go to "Routes"
- Create the following routes (all pointing to your Lambda function):
- GET / → Lambda function (serves the HTML interface)
- POST /send-attachment → Lambda function (handles file uploads)
- OPTIONS /{proxy+} → Lambda function (for CORS preflight requests)
- ANY /{proxy+} → Lambda function (catch-all for other routes, returns 404)
- For each route:
- Click "Create" → Enter the path and method
- Select your Lambda function as the integration target
- Click "Create"
-
Enable CORS (if not already configured)
- The Lambda function returns CORS headers, but you may want to configure CORS in API Gateway as well
- Go to "CORS" in your API settings
- Or ensure your Lambda function returns the appropriate CORS headers (already implemented)
-
Test Your Function
- Copy the API Gateway endpoint URL
- Visit it in your browser to see the upload interface
- Test uploading files and sending emails
- The zip file includes all production dependencies bundled
- Handler must be set to
handler.handler(file:handler.js, function:handler) - Ensure environment variables are set correctly
- API Gateway timeout should be at least 30 seconds for large attachments
- Consider increasing Lambda memory (1024 MB) for very large files (>10MB)
To remove the deployed Lambda function and API Gateway:
If using Serverless Framework:
npm run removeThis will delete:
- Lambda function
- API Gateway
- IAM roles and policies
- CloudWatch log groups
If uploaded manually:
- Delete the Lambda function from the Lambda Console
- Delete the API Gateway from the API Gateway Console
- Delete any associated IAM roles and CloudWatch log groups
This example is part of the Nylas Node.js SDK and is licensed under the MIT License.