Mailtrap Cloudflare Workers Integration

Mailtrap can be integrated with Cloudflare Workers for email sending, find out how to do it.

Before we start, you’ll need to:

Send emails using Cloudflare Workers and Mailtrap

To integrate Mailtrap and send emails via Cloudflare Workers, copy/paste the following script into your configuration:

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    try {
      const response = await fetch("https://send.api.mailtrap.io/api/send", {
        method: "POST",
        headers: {
          "Authorization": "Bearer YOUR-MAILTRAP-API-KEY-HERE",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          from: { name: 'Mailtrap Test', email: 'YOUR-EMAIL-HERE' },
          to: [{ email: 'RECIPIENT-EMAIL-HERE' }],
          subject: 'Hello World',
          html: '<strong>it works!</strong>',
        }),
      });

      const data = await response.json();

      return new Response(JSON.stringify(data), {
        headers: {
          'Content-Type': 'application/json',
        },
      });
    } catch (error) {
      return new Response(JSON.stringify({ 
        error: error instanceof Error ? error.message : 'Unknown error' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  },
};

Once you copy the script, make sure to insert your Mailtrap API token in the Authorization   header as a Bearer   token field 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