DEV Community

Olen Daelhousen
Olen Daelhousen

Posted on • Edited on

Using Nodemailer with Mailgun the Hard Way

I'm coding up an application powered by Node.js that will send several transactional emails to users including email account verification at sign up and receipts when they (hopefully) subscribe. As this is my first foray into high volume email, I do not want to commit to an email service right now. So, to make things easier if I decide to change email providers, instead of using Nodemailer's built in well-known services, I set up a custom transporter, shown in the below code snippet. Note the use of .env variables, in keeping with the Twelve Factor App Methodology.

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: process.env.SMTP_PORT,
    secure: process.env.SMTP_SECURE,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMPT_PASS
    },
    tls: {
      rejectUnauthorized: false
    }
  });

And now for the .env settings:

SMTP_HOST=smtp.mailgun.org
SMTP_PORT=465
SMTP_SECURE=true
SMTP_USER=postmaster@yourdomain.com
SMPT_PASS=yourSuperSecretMailgunPassword

I hope this helps someone else out there using Mailgun with Node and Nodemailer - there didn't seem to be very many examples incorporating Node in the official docs.

Top comments (0)