-
-
Save kom50/74729598e25aa0732828087c8b33f84b to your computer and use it in GitHub Desktop.
Send email using nodemailer with nunjucks template engine in Node.js using gmail service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
EMAIL_USER='your-email' | |
EMAIL_PASS='your-password' | |
EMAIL_HOST="smtp.gmail.com" | |
EMAIL_PORT=465 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Verification email</h1> | |
<p> | |
Please verify your email by clicking on the following link: | |
<a href="{{ url }}"> {{url}} </a> | |
</p> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import nodemailer from 'nodemailer'; | |
import dotenv from 'dotenv'; | |
import nunjucks from 'nunjucks'; | |
dotenv.config(); | |
const sendEmail = async options => { | |
const transporter = nodemailer.createTransport({ | |
service: 'gmail', | |
host: process.env.EMAIL_HOST, | |
port: process.env.EMAIL_PORT, | |
secure: true, | |
auth: { | |
user: process.env.EMAIL_USER, | |
pass: process.env.EMAIL_PASS, | |
}, | |
}); | |
const mailOptions = { | |
from: process.env.EMAIL_USER, | |
to: options.email, | |
subject: options.subject, | |
text: options?.message, | |
html: options?.html, | |
}; | |
await transporter.sendMail(mailOptions); | |
}; | |
const template = nunjucks.render('email.html', { url: 'http://localhost:3000/verify' }); | |
try { | |
await sendEmail({ | |
email: '<receiver email>', | |
subject: 'Verify Your Email', | |
html: template | |
}); | |
} catch (err) { | |
console.error('Error while sending email : ', err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment