Mailtrap AWS Lambda Integration

Mailtrap can be integrated with AWS Lambda functions for email sending, find out how to do it.

Before we start, you’ll need to:

Send emails using AWS Lambda and Mailtrap

To integrate Mailtrap and send emails via AWS Lambda, simply copy/paste the following script into your configuration:

/* global fetch */
const MAILTRAP_API_KEY = 'YOUR-MAILTRAP-API-KEY-HERE';

export const handler = async (event) => {
  try {
    const res = await fetch('https://send.api.mailtrap.io/api/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${MAILTRAP_API_KEY}`
      },
      body: JSON.stringify({
        from: { name: 'Mailtrap Test', email: 'YOUR-EMAIL-HERE' },
        to: [{ email: 'RECIPIENT-EMAIL-HERE' }],
        subject: 'Hello World',
        html: '<strong>it works!</strong>',
      })
    });

    if (res.ok) {
      const data = await res.json();

      return {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      };
    }

    return {
      statusCode: 400,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ error: `HTTP ${res.status}` }),
    };
  } catch (error) {
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        error: error instanceof Error ? error.message : 'Unknown error' 
      }),
    };
  }
};

Once you copy the script, make sure to insert your Mailtrap API token in the const MAILTRAP_API_KEY  line and enter your and your recipient's emails in the from:   and to:   fields.

Note: To learn more about API integration, click here.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us