To send an email using Node.js, you can use the nodemailer
library, which is a popular and easy-to-use module for sending emails. Here's a basic example of how you can send an email using Node.js and nodemailer:
-
Install nodemailer:
npm install nodemailer
-
Create a Node.js script with the following code:
const nodemailer = require('nodemailer'); // Create a transporter object using SMTP transport const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', // replace with your email pass: 'your_password' // replace with your password } }); // Email content const mailOptions = { from: '[email protected]', // sender address to: '[email protected]', // list of receivers subject: 'Test Email', // Subject line text: 'Hello, this is a test email!', // plain text body html: '
Hello, this is a test email!
' // HTML body }; // Send email transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Email sent: ' + info.response); });Make sure to replace
[email protected]
andyour_password
with your Gmail email and password. Note that using your password directly in the code is not recommended for production applications. Instead, consider using an "App Password" or OAuth for more secure authentication. -
Run the script:
node your_script_name.js
This is a basic example, and you may need to configure additional settings based on your email provider. Check the nodemailer documentation for more details: Nodemailer Documentation
Keep in mind that sending emails directly from your server might not be the best approach for a production environment. Consider using dedicated email services like SendGrid, Amazon SES, or others to handle email delivery in a more reliable and scalable way.