Send custom domain email notification - Node js

Published at: 2020-10-02 16:00:00

Updated at: 2023-10-17 12:28:59

email-notificationnodejs

Most of us will know how to send an email notification or just a simple email using gmail from Node JS. However, in this article I'm gonna show you how can you send an email using your own custom or registered domain name. (Eg: anyemail@lalapolalaanewb.com)

The setup is same for both process. You only need to change the sender information/email to make the changes as far as the code goes. But, don't worry. We gonna go step by step process to make this happen. But before that, if you feel more comfortable following this tutorials in video form. You may go to this link here, Send Custom Domain Email from Node JS - Nodemailer. But for those who wanna stay. You're welcome to do so too.

A. Setup Sending Email as Gmail Account

These are the only dependencies that we need to install in order to make this work:-

  • Express
  • Dotenv
  • Nodemailer

1st Step: Setup index.js

  • index.js:-
/** Dependencies */
// Express
const express = require('express')
const app = express()
// Dotenv
const dotenv = require('dotenv')
dotenv.config()
 
/** Global Middlewares */
// JSON Body Parser
app.use(express.urlencoded({ extended: false }))
 
/** Routes Middleware */
// Home
app.use('/', require('./routes/home'))
 
/** Server Startup */
app.listen(process.env.PORT || 3030, console.log(`Server is up & running at PORT ${process.env.PORT}!`))

2nd Step: Setup home routes

  • routes/home.js:-
/** Dependencies */
// Express Router
const router = require('express').Router()
// Email Handler
const { sendMail2Requestor } = require('../controllers/email')
 
/** Vars */
// Subscribe Users (should be using DB)
let users = []
 
/** Page Specific Functions */
// Home page Template
function homeTemplate(errorMessage) {
    return `
    <div style="position: relative; min-height: 100vh; display: flex; flex-flow: column; align-items: center; justify-content: center;">
        <h2 style="margin: 0;">Get Newsletter from us from NOW!</h2>
        <p>${errorMessage === null ? '' : errorMessage}</p>
        <form action="/" method="POST" style="position: relative; margin-top: 30px; display: flex; flex-flow: column; align-items: center; justify-content: center;">
            <input type="email" name="email" placeholder="Your Email" required/>
            <button type="submit" style="margin-top: 15px;">Submit</button>
        </form>
    </div>
`
}
 
/** Routes */
// HOME Get Route (Display Home page)
router.get('/', (req, res) => {
    // render Home page
    res.send(homeTemplate(null))
})
 
// HOME Post Route
router.post('/', async(req, res) => {
    let { email } = req.body
 
    // default error message
    let errorMessage = 'Successfully subscribe to our Newsletter!'
 
    // check if user already subscribed
    let userExist
    users.forEach(user => {
        if(user === email) userExist = true
        else userExist = false
    })
    if(userExist === true) return res.send(homeTemplate('You already subscribed to our Newsletter. Thanks for your subscription!')) 
 
    // send mail notification to Requestor (Customer)
    const requestorNoty = await sendMail2Requestor(email)
    if(requestorNoty === 'Unsuccessful!') errorMessage = errorMessage + 'Unfortunately, failed to send notification to your email.'
 
    // add user to subscribed list
    users.push(email)
 
    // re-render Home page
    res.send(homeTemplate(errorMessage))
})
 
/** Export */
module.exports = router
 

3rd Step: Setup email sending function

  • controllers/email.js:-
/** Dependencies */
// Nodemailer
const nodemailer = require('nodemailer')
 
/** Env Variables */
const {
    // Gmail's Email (Gmail Access)
    GMAIL_EMAIL = process.env.GMAIL_EMAIL,
    // Gmail Client ID
    CLIENT_ID = process.env.GMAIL_CLIENT_ID,
    // Gmail Client Secret
    CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET,
    // Gmail Refresh Token
    REFRESH_TOKEN = process.env.GMAIL_REFRESH_TOKEN
} = process.env
 
/** Email Functions Handler */
// REQUESTOR Noty Email
async function sendMail2Requestor(requestorEmail) {
    // - Create Nodemailer TRANSPORT INFO
    let transport = nodemailer.createTransport({
        // Service 
        service: 'Gmail',
        // Auth
        auth: {
            type: 'OAuth2',
            // Email use to send email (Your Google Email. Eg: xxx@gmail.com)
            user: GMAIL_EMAIL,
            // Get in Google Console API (GMAIL API)
            clientId: CLIENT_ID,
            // Get in Google Console API (GMAIL API)
            clientSecret: CLIENT_SECRET,
            // Get from Google OAuth2.0 Playground (Using Cliet ID & Client Secret Key)
            refreshToken: REFRESH_TOKEN
        }
    })
 
    // - body of Message
    let mailBody = `
        <div>
            <p>Hi! <b>${requestorEmail}</b></p>
            <p>Thank you for subscribing with us at https://lalapolalaanewb.com</p>
        </div>
        <div>
            <p>Sincerely,</p>
            <p>System [<b>Lalapolalaa Newb</b>]</p>
        </div>
    `
 
    // - Create BODY of mail
    let mailOptions = {
        // Email should be SAME as USER EMAIL above     
        from: `FMCalc System <${GMAIL_EMAIL}>`,
        // ANY Email to send the mail (to send to many use ',' inside the single quote. Eg: 'xxx@gmail.com, xxx@yahoo.com')
        to: requestorEmail,
        subject: `[Newsletter Subscription]`,
        // TEXT cannot apply any HTML Elements (use either TEXT or HTML)
        // text: 'Hey there, it’s our first message sent with Nodemailer ',
        // HTML can apply any HTML Elements (use either TEXT or HTML)
        html: mailBody
    }
 
    // send email
    return await transport.sendMail(mailOptions)
    .then(success => 'Successful!')
    .catch(err => 'Unsuccesful!')
}
 
/** Export */
module.exports = { sendMail2Requestor }

4th Step: Get clientId & clientSecret

  • Go to Google Console API. (just google it)

    • accept the Terms of Service, if only this is your first time using Google Console API. Then Agree and Continue
    • create your OAuth consent screen (on the left menu side bar). For first time user only.
    • Go to Library. (on the left menu side bar)
      • search for Gmail, and enable Gmail API
    • Go to Credentials. (on the left menu side bar)
      • +** Create Credentials**. (on the top menu - in blue color)
      • select OAuth client ID. (second choice)
      • Application type choose Web application
      • give any Name you want
      • on Authorized redirect URls, click on + ADD URl. (in blue color before CREATE button).
      • add https://developers.google.com/oauthplayground in the placeholder
      • click on CREATE
    • Copy both Your Client ID & Your Client Secret and paste it inside your .env in the code
  • .env:-

PORT = 3030
GMAIL_EMAIL = rookiegamer4life@gmail.com
GMAIL_CLIENT_ID = 37599559222-s94v2s21cpvekcce3vpls771mkf8a94g.apps.googleusercontent.com
GMAIL_CLIENT_SECRET = 0ytq8Vlk6LAzKtkYv9TBaUM0
GMAIL_REFRESH_TOKEN = 

5th Step: Get refreshToken

  • Go to url https://developers.google.com/oauthplayground/
    • click on Setting symbol. (right most corner of the page)
    • check on checkbox Use your own OAuth credentials
      • paste your previous Client ID in OAuth Client ID placeholder
      • paste your previous Client Secret in OAuth Client secret placeholder
    • Under Step 1 Select & authorize APIs. (first child of accordian left of the page)
      • insert https://mail.google.com/ and click Authorize APIs button (the one in blue color). You will be brought to a different page.
      • then select your Gmail account that you want to give permission of doing CRUD. (Allow and check all permission). You will be redirect back to the previous page.
    • Under Step 2 Exchange authorization code for tokens. (second child of accordian left of the page)
      • click on Exchange authorization code for tokens button. You will be automatically brought to the 3rd child of accordian (Just get back to the second child back)
      • check on the checkbox of Auto-refresh the token before it expires. (to make sure your token won't expire)
      • copy your ONLY the Refresh token and paste it in your .env file

6th Step: Store them all in .env

PORT = 3030
GMAIL_EMAIL = rookiegamer4life@gmail.com
GMAIL_CLIENT_ID = 37599559222-s94v2s21cpvekcce3vpls771mkf8a94g.apps.googleusercontent.com
GMAIL_CLIENT_SECRET = 0ytq8Vlk6LAzKtkYv9TBaUM0
GMAIL_REFRESH_TOKEN = 1//0fUUOmvhMot7MCgYIARAAGA8SNwF-L9IrajWkoaoYgDbKfS5pgHaH4LYwb9m8Bopad620llSEsKUv6tpv3ZQJJXHXhqRm1ZnLf7k

By now, you could already test your email notification sending. With above code, you will be sending the email notification as a gmail account user (Eg: anyemail@gmail.com). You may proceed to the next section to be able to send as other @anydomain.com instead just @gmail.com.

B. Setup Sending Email as @anydomain.com

You may want to see the video form of the second setup using a custom domain here, Send Custom Domain Email from Node JS - Nodemailer. Much easier to follow. But if you insist on following it here, in written form. You are welcomed to do so too.

Like I mentioned earlier, both setup is the same. but this time, on the code section, we just gonna (1) add SENDER_EMAIL & (2) change from email to SENDER_EMAIL in email.js file as shown below.

1st Step: Update email.js

  • updated controllers/email.js:-
/** Dependencies */
// Nodemailer
const nodemailer = require('nodemailer')
 
/** Env Variables */
const {
    // Gmail's Email (Gmail Access)
    GMAIL_EMAIL = process.env.GMAIL_EMAIL,
    // Sender's Email
    SENDER_EMAIL = 'fathi_noor@nitajsfera.com', // CHANGES MADE HERE (1) - any custom domain you added to your gmail
    // Gmail Client ID
    CLIENT_ID = process.env.GMAIL_CLIENT_ID,
    // Gmail Client Secret
    CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET,
    // Gmail Refresh Token
    REFRESH_TOKEN = process.env.GMAIL_REFRESH_TOKEN
} = process.env
 
/** Email Functions Handler */
// REQUESTOR Noty Email
async function sendMail2Requestor(requestorEmail) {
    // - Create Nodemailer TRANSPORT INFO
    let transport = nodemailer.createTransport({
        // Service 
        service: 'Gmail',
        // Auth
        auth: {
            type: 'OAuth2',
            // Email use to send email (Your Google Email. Eg: xxx@gmail.com)
            user: GMAIL_EMAIL,
            // Get in Google Console API (GMAIL API)
            clientId: CLIENT_ID,
            // Get in Google Console API (GMAIL API)
            clientSecret: CLIENT_SECRET,
            // Get from Google OAuth2.0 Playground (Using Cliet ID & Client Secret Key)
            refreshToken: REFRESH_TOKEN
        }
    })
 
    // - body of Message
    let mailBody = `
        <div>
            <p>Hi! <b>${requestorEmail}</b></p>
            <p>Thank you for subscribing with us at https://lalapolalaanewb.com</p>
        </div>
        <div>
            <p>Sincerely,</p>
            <p>System [<b>Lalapolalaa Newb</b>]</p>
        </div>
    `
 
    // - Create BODY of mail
    let mailOptions = {
        // Email should be SAME as USER EMAIL above     
        from: `FMCalc System <${SENDER_EMAIL}>`, // CHANGES MADE HERE (2)
        // ANY Email to send the mail (to send to many use ',' inside the single quote. Eg: 'xxx@gmail.com, xxx@yahoo.com')
        to: requestorEmail,
        subject: `[Newsletter Subscription]`,
        // TEXT cannot apply any HTML Elements (use either TEXT or HTML)
        // text: 'Hey there, it’s our first message sent with Nodemailer ',
        // HTML can apply any HTML Elements (use either TEXT or HTML)
        html: mailBody
    }
 
    // send email
    return await transport.sendMail(mailOptions)
    .then(success => 'Successful!')
    .catch(err => 'Unsuccesful!')
}
 
/** Export */
module.exports = { sendMail2Requestor }

2nd Step: Add Custom Domain Email to Gmail Account

  • Get your Mail Client Manual Settings from @anydomain.com cpanel (Eg: @nitajsfera.com/cpanel) Assuming you already have any domain purchased or registered and created an email

blog_sendCustomDomainEmail_1

  • Go to Gmail Setting

blog_sendCustomDomainEmail_2

  • Go to Accounts and Import

blog_sendCustomDomainEmail_3

  • Click on Add a mail account under Check mail from other accounts

blog_sendCustomDomainEmail_4

  • Follow through below images:-

blog_sendCustomDomainEmail_5.1 blog_sendCustomDomainEmail_5.2 blog_sendCustomDomainEmail_5.3 blog_sendCustomDomainEmail_5.4 blog_sendCustomDomainEmail_5.5 blog_sendCustomDomainEmail_5.6 blog_sendCustomDomainEmail_5.7 blog_sendCustomDomainEmail_5.8

Now, you're able to send as anyemail@anydomain.com. As long as other email accounts can be incorporate(send & receiving emails) with your Gmail account. Then, there will be no problem to implement this method.

Anyway, that's all for today's topic. As always, thanks for being here. Until next time, Chao! Salam.