how to send email in javascript

To send an email in JavaScript, we can use the nodemailer package. First, we need to install it using npm by running the following command:

npm install nodemailer

Next, we can use the following code to send an email using Gmail SMTP:

index.tsx
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your_email@gmail.com',
        pass: 'your_password'
    }
});

// setup email data with unicode symbols
let mailOptions = {
    from: '"Sender Name" <sender_email@gmail.com>', // sender address
    to: 'recipient_email@example.com', // list of receivers
    subject: 'Subject of your email', // Subject line
    text: 'Plain text version of your email', // plain text body
    html: '<p>HTML version of your email</p>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        console.log(error);
    } else {
        console.log('Message %s sent: %s', info.messageId, info.response);
    }
});
886 chars
29 lines

Note: In order to use Gmail SMTP, you need to enable Less Secure Apps in your Google account's security settings. Alternatively, you can use Gmail API for authenticated email sending.

gistlibby LogSnag