Send transactional emails with Mailgun

To use the Mailgun integration to send transactional emails 3 environment variables are required:

  • MAILGUN_API_KEY - Your Mailgun API key is found on the Mailgun API security page.
  • MAILGUN_URL - This value can only be one of 2 values. https://api.mailgun.net if you're using the US infrastructure or https://api.eu.mailgun.net if you're using the EU infrastructure. The default value is https://api.mailgun.net.
  • MAILGUN_DOMAIN - If you connected your custom domain to Mailgun this value should be your custom domain. Otherwise, it will be a sandbox domain provided by Mailgun e.g. sandbox5519009eb6444178dc94b9214036072.mailgun.org.

Once you configured these values as environment variables you can use the two functions to either send plain text emails or pre-built template emails.

To send plain text emails use the following function:

import { sendPlainTextMail } from '@/utils/emails/mailgun'

...

await sendPlainTextMail(
  'to-email@test.com',                      // to email address
  'from-email@test.com',                    // from email address - usually an email address from your company
  'Subject of email',                       // email subject
  'Email body - hey this is a test email',  // plain text body of email
)

To send an email using a pre-built Mailgun template use the following function:

import { sendTemplateMail } from '@/utils/emails/mailgun'

...

await sendTemplateMail(
  'to-email@test.com',                // to email address
  'from-email@test.com',              // from email address - usually an email address from your company
  'Subject of email',                 // email subject
  'email-template-name',              // name of email template on Mailgun
  {                                   // dynamic template data configured in Mailgun email templates
    propName1: 'test value',
    propName2: 'another test value',
  }
)
Last updated:

Want to know how to easily build your SaaS?

Sign up for the Ship SaaS newsletter to get notifiedabout the latest updates and blog posts

We care about the protection of your data. Read our Privacy Policy and Terms & Conditions.