Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lauslim12/df25e3d0e6f2ca563977dfa05563aae7 to your computer and use it in GitHub Desktop.
Save lauslim12/df25e3d0e6f2ca563977dfa05563aae7 to your computer and use it in GitHub Desktop.
Explains how to use Nodemailer without toggling 'Less Secure App Access' and/or use OAuth2.

Nodemailer

We have got a bit of a problem. How do I use nodemailer without toggling 'Less Secure App Access' and/or using OAuth2 in Google Developers?

Answer

Google developed a concept called App Passwords, and it's something that you can use in order to circumvent this issue.

Below are the steps you need to take:

  • For the whole steps, I recommend you to use Incognito mode.
  • Log in to your Google Account.
  • Go to 'My Account' -> 'Security'.
  • Enable Two-Step Verification in your Google Account.
  • Create an App Password. Give it a good name and copy your code.
  • In your application code, use the following snippet (simplified for brevity):
import nodemailer from 'nodemailer';

// Create a default transport, let Nodemailer handle everything in its
// implementation detail.
const transport = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 465,
  auth: {
    user: '<YOUR_GMAIL_ADDRESS>',
    pass: '<YOUR_APP_PASSWORD>',
  },
});

// Verify your connection.
transport.verify((err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Nodemailer with Gmail is ready to process mails.');
  }
});

// Send an email!
transport.sendMail({
  from: '<YOUR_GMAIL_NAME>',
  to: '<TO_EMAIL_ADDRESS>',
  subject: 'Test email from Nodemailer!',
  html: '<p>Hello World, Email works!</p>',
  text: 'Hello World, Email works!',
});

Security and Best Practices

Q: What if someone manages to hack into my server and successfully stole my app password?

  • Revoke it from your Google Account. If someone manages to breach into your back-end servers, you may have to perform security audits, though!

Q: What is the best practices for sending emails?

  • Use a queue. Technologies like BullMQ is very good for email processing, as both 'rendering emails' and 'sending emails' are taking a bit of time. Don't forget to use environment variables as well, as your mailserver, your username, password, and the like are probably secrets.

Q: What if I don't want to use an App Password?

  • Use either 'Less Secure App Access' and/or OAuth2.

Q: What is the better way of using Gmail?

  • Well, you can use Gmail API or you can also use OAuth2 as your authentication. OAuth2 is very secure, but there is a bit of technical complexity and you may have to verify your app as well (IIRC, OAuth2 is free for first few refresh tokens, but any more than that and you will have to verify your app to Google).

Hopefully, this solution works for you guys as well.

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment