/

How to Send an Email Using Nodemailer

How to Send an Email Using Nodemailer

If you want to send an email using Nodemailer, follow these steps:

Step 1: Install Nodemailer

Begin by installing Nodemailer using npm:

1
npm install nodemailer

Step 2: Import Nodemailer

Next, import the Nodemailer module in your Node.js script or application:

1
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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
transporter.sendMail(options, (err, info) => {
if (err) {
console.log(err);
} else {
console.log('EMAIL SENT');
}
});

Alternatively, you can use the promise-based syntax:

1
const info = await transporter.sendMail(options);

Full Example Code

Here’s the full example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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