If you want to send an email using Nodemailer, follow these steps:
Step 1: Install Nodemailer
Begin by installing Nodemailer using npm:
npm install nodemailer
Step 2: Import Nodemailer
Next, import the Nodemailer module in your Node.js script or application:
import nodemailer from 'nodemailer';
Step 3: Initialize the Transporter
Create a transporter object that will be used to send the email. Here’s an example:
const transporter = nodemailer.createTransport({
host: 'smtp.yoursmtpserver.com',
port: 465,
secure: true,
auth: {
user: 'smtp_user',
pass: 'smtp_pass',
},
});
⚠️ NOTE: Make sure to replace
'smtp_user'
and'smtp_pass'
with the actual credentials of your SMTP server.
Step 4: Create the Email Options
Now, create an options
object to specify the details of the email you want to send:
const options = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hi!',
html: '<p>Hello</p>',
};
Step 5: Send the Email
Finally, use the sendMail()
method on the transporter
object to send the email. Pass the options
and a callback function that will be executed when the email is sent:
transporter.sendMail(options, (err, info) => {
if (err) {
console.log(err);
} else {
console.log('EMAIL SENT');
}
});
Alternatively, you can use the promise-based syntax:
const info = await transporter.sendMail(options);
Full Example Code
Here’s the full example code:
import nodemailer from 'nodemailer';
const sendEmail = () => {
const transporter = nodemailer.createTransport({
host: 'smtp.yoursmtpserver.com',
port: 465,
secure: true,
auth: {
user: 'smtp_user',
pass: 'smtp_pass',
},
});
const options = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hi!',
html: '<p>Hello</p>',
};
transporter.sendMail(options, (err, info) => {
if (err) {
console.log(err);
} else {
console.log('EMAIL SENT');
}
});
}
That’s it! You now know how to send an email using Nodemailer.
Tags: Nodemailer, Email, SMTP, Node.js