Skip to content

Instantly share code, notes, and snippets.

@kom50
Last active June 1, 2024 16:03
Show Gist options
  • Save kom50/74729598e25aa0732828087c8b33f84b to your computer and use it in GitHub Desktop.
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
EMAIL_USER='your-email'
EMAIL_PASS='your-password'
EMAIL_HOST="smtp.gmail.com"
EMAIL_PORT=465
<h1>Verification email</h1>
<p>
Please verify your email by clicking on the following link:
<a href="{{ url }}"> {{url}} </a>
</p>
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