cloud

Sending Emails with Nodemailer and GMail

Prerequisites


Configure secure GMail access

  1. 'Open https://console.cloud.google.com/home
  2. Press New Project
  3. Insert project name - Location can be left empty - Click "Create"
  4. Now the project should be selected like that
  5. Select "APIs & Services" - "OAuth consent screen"
  6. Select External and click "Create"
  7. Enter mandatory fields "App name" / "User support mail" / "Developer contact information" - click "Save And Continue"
  8. Skip the Scopes page with again clicking "Save and Continue"
  9. Add Test User clicking on "+ Add Users"
  10. Select "Credentials" form the left menue

  11. Create Credentials for OAuth client ID
  12. Select "Application type" - Web application
  13. Add https://developers.google.com/oauthplayground at "Authorized redirect URIs" with clicking "+ Add URI" and then click "Create"
  14. You now should see your Client-ID and Client-Secret - we need them later - press "OK"
  15. Open OAuth 2.0 Playground: https://developers.google.com/oauthplayground/
  16. Select on the left side "Gmail API v1" and there "https://mail.google.com" and click "Authorize APIs"
  17. Select your GMail-Account you want to use

  18. Allow permissions
  19. Allow again - to work with emails from GMail

  20. Click on "Exhange authorization code for tokens" to get Refresh Token and Access Token


Setup the environment-variables and .gitignore

(its important that you NEVER write such secure informations directly in a code which can be unindentionally uploaded to eg. GitHub - allways use instead dotenv and hidden-files like .env which should never get uploaded anywhere stays only locally)

OAUTH_CLIENTID=yourClientID
            OAUTH_CLIENT_SECRET=yourClientSecret
            OAUTH_REFRESH_TOKEN=yourRefreshToken
            MAIL_USERNAME=yourGMailAdress
            MAIL_PASSWORD=yourGMailPassword
            
.env
            node_modules
            

Do the Coding

const express = require('express')
            const nodemailer = require('nodemailer');
            require("dotenv").config({ path: "./.env" });
            const { gmail } = require('googleapis/build/src/apis/gmail')
            
const app = express()
            const port = 3000
            app.listen(port, () => {
              console.log(`nodemailerProject is listening at http://localhost:${port}`)
            })
            
let transporter = nodemailer.createTransport({
              service: 'gmail',
              auth: {
                type: 'OAuth2',
                user: process.env.MAIL_USERNAME,
                pass: process.env.MAIL_PASSWORD,
                clientId: process.env.OAUTH_CLIENTID,
                clientSecret: process.env.OAUTH_CLIENT_SECRET,
                refreshToken: process.env.OAUTH_REFRESH_TOKEN
              }
            });
            
let mailOptions = {
              from: process.env.MAIL_USERNAME,
              to: "[email protected]",
              subject: 'Nodemailer Test Project',
              text: 'Hallo from my nodemailer project'
            };
            
transporter.sendMail(mailOptions, function(err, data) {
              if (err) {
                console.log("Error " + err);
              } else {
            ### console.log("Email sent successfully");
              }
            });
            

Find the full code here: https://github.com/Rapid1898-code/exampleNodeMailerGMail

If you have any questions or suggestions please get in contact with me: MAIL