Skip to content

tcanbolat/Nodemailer-with-Gmail-and-OAuth2-Cheat-Sheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nodemailer-with-Gmail-and-OAuth2-Cheat-Sheet

This App demonstrates how to set up Nodemailer using Gmail & OAuth2.

nodeMailer Gmail OAuth2




Breakdown of Instructions

Part One: Create a new app

Part Two: Obtain Gmail OAuth2

Part Three: Run app!



Part One

Create new App

- Clone repo to local drive
- npm install

OR create a new folder

- touch app.js
- npm init
- npm install nodemailer

within app.js add the dependencies.

const nodemailer = require("nodemailer");

next create a output variable that will contain your message.

const output = `
  <h1>New Messsage!<h1>
  <p>I hope this works.</p>
`;

Now create the transporter function. This function is where you will add in your OAuth2 credentials further down.

let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
   type: "OAuth2",    // defining the authentication type
   clientId: "************",    // this will be obtained in part 2
   clientSecret: "************",    // this will be obtained in part 2     
  },
});

in the same file under the transporter function, create a mailOptions variable.

let mailOptions = {
  from: "Your nodeMailer app!",   // You can change this to whatever you like. !this is NOT where you add in the email address!
  to: "[email protected]",    // Use your same googele email ("send yourself an email") to test if the app works.
  subject: "Testing123...",   // change the subject to whatever you like.
  html: output,   // this is the output variable defined earlier that contains our message.
  auth: {
   user: "[email protected]",   // replace this with your google email
   refreshToken: "************",    // this will be obtained in part 2 
   accessToken: "************",    // this will be obtained in part 2 
   expires: new Date().getTime(),  // this will request a new token each time so that it never expires. google allows up to 10,000 requests per day for free.
  },
};

Finally, create the function that will send your email!

transporter.sendMail(mailOptions, (error, info) => {  
  if (error) {
    console.log(error);   // if anything goes wrong an error will show up in your terminal.
  } else {
      console.log("Message sent: %s", info.messageId);    // if it's a success, a confirmation will show up in your terminal.
    }
});


Part Two

Obtain OAuth2 credentials

  • head on over to: https://console.developers.google.com/
  • Click on Select a project in the top left corner.
  • A pop up will appear, click on NEW PROJECT
  • Create a name for your project

  • You will then be redirected back to the dashboard
  • To the left of the screen, click on "OAuth consent screen"
  • Click on external, then add in you app name again in the input field, THEN click the blue save button at the bottom of the page

  • To the left of the screen, click on credentials
  • Then, click on "+ CREATE CREDENTIALS" and select "OAuth client ID"
  • Choose Web Application, THEN! in the "Authorized redirect URIs" input field copy/paste this link: https://developers.google.com/oauthplayground
  • Click on create, might have to click twice"

  • You will be redirected to a pop up that has your client ID and client secret
  • Add these credentials to your transporter function!

  • Head on over to https://developers.google.com/oauthplayground
  • Click on the setting button to the right
  • Click on "Use your own OAuth credentials" and then add your client ID as well as your client secret in the input fields
  • Dont close out of settings!

  • To the left, in the input filed add in "https://www.googleapis.com/auth/gmail.send" and click Authorize API's
  • this will only allow the app to send emails and nothing else
  • When you get redirected if the pop up asks what account you want to use, choose the one that you want to send emails with, if not then that means you only have one google account setup on your machine.

  • You will then see a pop up with a red ALERT!, this is only asking if we want the app to access our gmail account
  • Just click on Advanced to the left, and click on the very bottom link that has your appname(unsafe)
  • Dont worry, its only alerting you because google hasn't verified your app that you just created in developers.google
  • Click on allow and you will be redirected back to the OAuth screen

  • Here, click on the "Exchange authorization code for tokens" and your tokens will be generated below
  • It might automatically switch to the next tab, if so just click on the earlier tab for Exchange Authorization tokens

  • Now, take the access token and the refresh token and add them to your transporter function
  • Congrats! Your app is all set up to start sending emails using OAuth2!


Part Three

Run App!

If you haven't already, add in your OAuth2 credentials to the transporter function.

In your terminal run

node app.js

You should now see an error or a confirmation in the terminal.

If you got a Confirmation, go on over to your Gmail inbox and you should see the email that your app just sent.



ADVICE!

Make sure to hide your OAuth2 credentials before you push your code to GitHub or anywhere else.

Look up "dotenv" npm module to hide your variables locally. https://www.npmjs.com/package/dotenv

Troubleshooting

If your still running into trouble, try some of these steps

  1. Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and click on continue. then go back and try sending the email through your app again, at least twice.
  2. You can also allow more access to your app, earlier we copy/pasted https://www.googleapis.com/auth/gmail.send so that we could allow the app to send emails using our google credentails. Instead go back and change it to https://www.googleapis.com/auth/gmail. This will give your app more access to your gmail and maybe solve your error.
  3. If your getting an error about your login being invalid, Your Gmail password might be to weak for OAuth2 and its not letting you go through. Try changing your password and it might solve the issue. (this fixed my issue).
  4. You can also try allowing less secure apps to access your google account, but that would defeat the purpose of OAuth2 and leave you potentially vulnerable. If you want to test it out, go over to https://myaccount.google.com/lesssecureapps and toggle to allow.


Written by Abdullah Canbolat

About

This App demonstrates how to set up Nodemailer using Gmail & OAuth2. Follow the steps listed in the ReadMe and you'll be sending emails in no time!

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published