To send an email in Node.js, you can use a popular npm package called nodemailer. Here is a basic example of how to send an email using nodemailer:
- First, you need to install nodemailer by running the following command in your terminal:
npm install nodemailer
2. After installing nodemailer, you can use it in your Node.js application by requiring it at the top of your file:
const nodemailer = require(‘nodemailer’);
3. Then, create a transporter object with the email provider details. Here is an example for Gmail:
let transporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: ‘your-email@gmail.com’,
pass: ‘your-email-password’
}
});
Note that you need to replace ‘your-email@gmail.com‘ and ‘your-email-password’ with your own email address and password.
- Now you can create an email message object with the details of your email, such as the recipient, subject, and body:
let mailOptions = {
from: ‘your-email@gmail.com’,
to: ‘recipient-email@example.com’,
subject: ‘Hello from Node.js’,
text: ‘This is a test email sent from a Node.js application.’
};
Note that you need to replace ‘your-email@gmail.com‘ with your own email address, and ‘recipient-email@example.com‘ with the email address of the recipient.
- Finally, use the transporter object to send the email by calling the sendMail method and passing in the mailOptions object:
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
This will send the email and log a message to the console indicating whether it was successful or not.
Here is the full code example:
const nodemailer = require(‘nodemailer’);
let transporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: ‘your-email@gmail.com’,
pass: ‘your-email-password’
}
});
let mailOptions = {
from: ‘your-email@gmail.com’,
to: ‘recipient-email@example.com’,
subject: ‘Hello from Node.js’,
text: ‘This is a test email sent from a Node.js application.’
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
Leave a Reply