If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To send HTML template emails using Nodemailer, we first need to create an HTML template that we want to send. Let's create a sample HTML template file called template.html
:
htmlCopy code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to our Website</title>
</head>
<body>
<h1>Welcome to our Website</h1>
<p>Dear {{ name }},</p>
<p>Thank you for signing up on our website.</p>
<p>We hope you have a great experience with us!</p>
</body>
</html>
In the above HTML template, we are using a template variable {{ name }}
, which we will replace with the actual name of the recipient when we send the email.
Next, we need to configure Nodemailer to use our SMTP server and set up the transporter:
javascriptCopy code
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'your-email-password'
}
});
In the above code, we are using Gmail SMTP to send emails. You should replace the user
and pass
values with your own Gmail email address and password.
Now, let's write a function to send the email using the HTML template:
javascriptCopy code
async function sendWelcomeEmail(email, name) {
try {
const info = await transporter.sendMail({
from: 'Your Name <[email protected]>',
to: email,
subject: 'Welcome to our Website',
html: `
<h1>Welcome to our Website</h1>
<p>Dear ${name},</p>
<p>Thank you for signing up on our website.</p>
<p>We hope you have a great experience with us!</p>
`
});
console.log(`Email sent: ${info.messageId}`);
} catch (error) {
console.log(error);
}
}
In the above code, we are using the transporter.sendMail()
method to send the email. We have set the from
, to
, subject
and html
fields of the email. We have used string interpolation to replace the {{ name }}
variable in the HTML template with the actual name of the recipient.
We have also added a try-catch block to handle any errors that may occur during sending the email.
To send the email, you can call the sendWelcomeEmail()
function and pass in the email and name of the recipient:
javascriptCopy code
sendWelcomeEmail('[email protected]', 'John');
This will send the welcome email to the email address [email protected]
with the recipient's name set to John
.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.