Mailgun

Sending Emails from Applications using Mailgun

Mailgun

by John Vincent


Posted on September 2, 2023


Sending emails with Mailgun is straightforward.

Overview

Mailgun

Google Domains

MXToolBox

GoogleAdminToolBox

Google Admin Console

Configuring DMARC for Google Workspace

Introduction

Previously I used Nodemailer and Gmail to send emails. For details, see Sending Emails from Express Application and Google Gmail Configuration. For a variety of reasons, I chose to move away from Gmail.

Mailgun

Mailgun

  • Sign up for an account

A sandbox domain will be provided which is useful for basic development and verification of the environment.

However, for proper application usage, it is necessary to

  • Upgrade

Now it is possible to create a custom domain.

  • Dashboard
  • Domains
    • Add New Domain

I chose to use a domain I already own, thus

  • Domain Name: mg.my-domain.com
  • US
  • 1024

When the domain is added, some DNS changes are required to the my-domain.com domain.

Add DNS entries

From Mailgun Dashboard

  • Select domain mg.my-domain.com
  • Select Domain Settings
  • Select DNS records

Notice the SPF, DKIM, MX and CNAME records. These need to be added as DNS entries to the domain.

Add the following DNS records

Type: CNAME
Hostname: email.mg
Value: mailgun.org

Type: TXT
Hostname: mg
Value: v=spf1 include:mailgun.org ~all

Type: TXT
Hostname: pic._domainkey.mg
Value: paste value here

Type: MX
Hostname: mg
Value: mxa.mailgun.org

Type: MX
Hostname: mg
Value: mxb.mailgun.org

Using Google Domains, the changes are propagated almost immediately.

See section 4, Wait for your domain to verify

  • Verify DNS Settings.

Once the DNS settings have been verified, Mailgun is ready for use.

Verify SPF and DKIM

To verify these are working:

  • MXToolBox
  • Choose SPF Record Lookup
  • Enter mg.johnvincent.io

should show

v=spf1 include:mailgun.org ~all
  • Choose DKIM Lookup
  • Enter pic._domainkey.mg.johnvincent.io

should show

v=DKIM1; k=rsa; p= ........ 

Search for DMARC record

  • MXToolBox
  • Choose DMARC Lookup
  • Enter mg.johnvincent.io

should show

No DMARC Record found

Add DMARC record

To add a basic DMARC DNS record

Create new record

  • Host name: _dmarc.mg
  • Type: TXT
  • TTL: 1 hour
  • Data: v=DMARC1; p=none; pct=100; sp=none; rua=mailto:postmaster@johnvincent.io; adkim=r; aspf=r

Retest with MXToolBox

Reports

Reports will be sent to postmaster@johnvincent.io. Ensure the email id has been created.

Lookup your Mailgun API Keys

  • Dashboard
  • API Keys (on the right)
  • Copy the Private API key and paste into the code below.

Code

The following is fairly self explanatory.

Configuration code in config.js

const CONFIG = {
	MAILGUN: {
		apiKey: 'your-mailgun-api-key',
		domain: 'your-mailgun-domain'
	}
};

exports.CONFIG = CONFIG;

Sending emails with Mailgun in email.js

const Mailgun = require('mailgun-js');

const { CONFIG } = require('./config');
const { APPLICATION_NAME, MAIL_FROM_EMAIL, MAIL_SUPPORT_EMAIL, MAIL_TEST_EMAILS } = CONFIG;

....

	handleTestEmails() {
		const subject = `${APPLICATION_NAME}; Email Testing`;
		const text = `Testing the email system`;
		const html = `<h1>Email Test</h1><p>Testing message for ${APPLICATION_NAME}</p>`;
		const emailData = {
			from: `${MAIL_FROM_EMAIL}`,
			subject,
			text,
			html
		};
		MAIL_TEST_EMAILS.forEach(emailId => {
			console.log('emailId ', emailId);
			emailData.to = `${emailId}`;
			this.sendEmail(emailData);
		});
	}

	sendEmail(emailData) {
		logger.info('--- config/email::sendEmailWithMailgun, emailData ', emailData);

		const { MAILGUN } = CONFIG;

		const mailgun = new Mailgun({apiKey: MAILGUN.apiKey, domain: MAILGUN.domain});

		logger.info(`Attempting to send email from ${emailData.from}`);
		mailgun.messages().send(emailData, (err, body) => {
			if (err) {
				logger.error(`Problem sending email: ${err}`);
				console.log("got an error: ", err);
			}
			else {
				logger.info(`Email sent; body `, body);
			}
		});
	}