This is a quick example of how to send an email in Node.js using the nodemailer email sending module.

For more info on nodemailer see https://nodemailer.com/.

Installing nodemailer from npm

With the npm CLI: npm install nodemailer

With the yarn CLI: yarn add nodemailer

Sending an HTML email in Node.js

This code sends a simple HTML email using the Ethereal free SMTP testing service, you can create a free test account in one click at https://ethereal.email/ and copy the username and password from below the title Nodemailer configuration. See instructions below for using different SMTP providers such as Gmail and Hotmail.

// create transporter object with smtp server details
const transporter = nodemailer.createTransport({
    host: 'smtp.ethereal.email',
    port: 587,
    auth: {
        user: '[USERNAME]',
        pass: '[PASSWORD]'
    }
});

// send email
await transporter.sendMail({
    from: 'from_address@example.com',
    to: 'to_address@example.com',
    subject: 'Test Email Subject',
    html: '<h1>Example HTML Message Body</h1>'
});

Sending a plain text email in Node.js

This code sends the same email as above with a plain text body.

// create transporter object with smtp server details
const transporter = nodemailer.createTransport({
    host: 'smtp.ethereal.email',
    port: 587,
    auth: {
        user: '[USERNAME]',
        pass: '[PASSWORD]'
    }
});

// send email
await transporter.sendMail({
    from: 'from_address@example.com',
    to: 'to_address@example.com',
    subject: 'Test Email Subject',
    text: 'Example Plain Text Message Body'
});

Changing SMTP Provider (e.g. Gmail, Hotmail, Office365)

To change the above code to use a different email provider simply update the host parameter passed to the nodemailer.createTransport() method, for example:

// gmail
const transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    ...
});

// hotmail
const transporter = nodemailer.createTransport({
    host: 'smtp.live.com',
    ...
});

// office 365
const transporter = nodemailer.createTransport({
    host: 'smtp.office365.com',
    ...
});

#node #javascript #developer

How to Send an Email in Node.js via SMTP with Nodemailer
109.80 GEEK