Mailgun

Sending Emails from Applications using Mailgun

Mailgun

by John Vincent


Posted on May 1, 2019


Sending emails with Mailgun is straightforward.

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 the following 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

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.

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);
            }
        });
    }