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 (1)

Collapse
 
tylerlwsmith profile image
Tyler Smith

This was super helpful. Most of the pages that discussed using Mailgun with Nodemailer recommended nodemailer-mailgun-transport, but I figured there had to be some way to do it without a third-party package.

It took me a minute to get this working: I was getting the following error:

[Error: 4032840102000000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:355:
] {
  library: 'SSL routines',
  reason: 'wrong version number',
  code: 'ESOCKET',
  command: 'CONN'
}
Enter fullscreen mode Exit fullscreen mode

That's because I was using port that Mailgun recommends: port 587. I hunted and found this GitHub issue that recommended port 465, then I realize that's what you had in your article and I wasn't paying attention 😅

Thanks for publish this blog post!