send an email with gmail in javascript

To send an email with Gmail in JavaScript, you can use the nodemailer library which provides an easy way to send emails using various email services.

Before proceeding, you need to set up an app-specific password in your Gmail account. This is required because Gmail considers the use of a password by third-party apps as less secure than using your main account password. You can find instructions on how to set up an app-specific password in the Gmail Help Center.

Once you have set up the app-specific password, you can use the following code to send an email:

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

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

// setup email data
let mailOptions = {
    from: 'yourEmailAddress@gmail.com', // sender address
    to: 'recipientEmailAddress@gmail.com', // list of receivers
    subject: 'Hello from Node.js!', // Subject line
    text: 'Hello World!', // plain text body
    html: '<b>Hello World!</b>' // html body
};

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

In the above code, we are creating a transporter object using nodemailer with the service set to Gmail and adding the Gmail credentials (email address and app-specific password) to the auth field.

We then setup the email data including from, to, subject and text (plain text message) and html (HTML message), which is optional.

Finally, we call the sendMail function with the mailOptions object and a callback function to handle errors and success.

gistlibby LogSnag