How to use a hosting email with Nodemailer in a Node.js application
In case a Hostinger email is not created, first create the Hostinger email by reading this article:
Step 1:
Install Nodemailer: First, ensure you have Node.js installed on your machine. Then, you can install Nodemailer using npm:
choose any folder of Ubunt/Window/MaC, run below command (T&C node install in your system)
npm install nodemailer
Step 2:
Create a transporter: You’ll need to configure a transporter, which is the service that will send the email. The configuration will depend on the email hosting provider you’re using (e.g., Gmail, Outlook, custom SMTP server)
In this case we are using NodeMailer through which we can sent email
Step 3:
Set Up the Project
mkdir my-email-project
cd my-email-project
npm init -y
Install Nodemailer:
cd my-email-project
npm install nodemailer
create file sendEmail.js
nano sendEmail.js
Paste below code in the sendEmail.js file
const nodemailer = require('nodemailer');
// Replace these with your email hosting provider's SMTP settings
const transporter = nodemailer.createTransport({
host: 'smtp.hostinger.com', //
port: 587, // Port for TLS if not then try 586
secure: false, // True for port 465, false for other ports
auth: {
user: 'no-reply@researchthinker.com', // Your email address
pass: 'test@1234', // Your email password
},
});
// Verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
const sendMail = async () => {
try {
let info = await transporter.sendMail({
from: 'no-reply@researchthinker.com', // Sender address
to: 'no-reply@researchthinker.com', // List of recipients
subject: 'Hello', // Subject line
text: 'Hello world?', // Plain text body
html: '<b>Hello world?</b>', // HTML body
});
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
} catch (error) {
console.error('Error sending email:', error);
}
};
sendMail();
Output
my-email-project % node sendEmail.js
Server is ready to take our messages
Message sent: <0938-6548-18c8-f9ef-2f856d566d26@researchthinker.com>
Preview URL: false