Published at: 2020-10-02 16:00:00
Updated at: 2023-10-17 12:28:59
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.
These are the only dependencies that we need to install in order to make this work:-
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}!`))
home
routesroutes/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
email
sending functioncontrollers/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 }
clientId
& clientSecret
Go to Google Console API. (just google it)
.env
:-
PORT = 3030
GMAIL_EMAIL = rookiegamer4life@gmail.com
GMAIL_CLIENT_ID = 37599559222-s94v2s21cpvekcce3vpls771mkf8a94g.apps.googleusercontent.com
GMAIL_CLIENT_SECRET = 0ytq8Vlk6LAzKtkYv9TBaUM0
GMAIL_REFRESH_TOKEN =
refreshToken
.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.
@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.
email.js
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 }
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.