DEV Community

Cover image for Send email with nodejs
Patrick Zocli
Patrick Zocli

Posted on

Send email with nodejs

Prerequisites

  • an e-mail address (to be used for sending e-mails)
  • the package nodemail

    npm install nodemail
    
    # For typescript projects
    npm install nodemail @types/nodemail
    

The email address used must have « 2-factor authentication enabled ». To find out how to activate it, click here: 2-factor authentication

Also, you'll need to provide nodemail with your account authentication information. This includes your email address and a password, but not just any password.

Google has a platform that allows you to generate separate passwords. These passwords are only used for third-party services such as email clients, email applications (like Nodemailer), and other tools that require secure access to your Google Account.

To do this, you need to :

💡 If the interface is empty, this means you haven't activated 2-factor authentication

Development

First, here's a complete example for those of you who understand quickly. Let's say you want to send a nice email to several friends. Here's how to do it:

const nodemailer = require('nodemailer');

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

// setup email data with unicode symbols
let mailOptions = {
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: 'bar@example.com, baz@example.com', // list of receivers
    subject: 'Hello ✔', // 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) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});

Enter fullscreen mode Exit fullscreen mode

Don't forget to replace your.email@gmail.com and your_password with your own authentication information.

Explanation

  1. Import module :

    const nodemailer = require('nodemailer');
    
    

    We start by importing nodemailer. Of course, you can also use the ES6 syntax import nodemail from 'nodemail';

  2. Create a "transporter" :

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'your.email@gmail.com',
            pass: 'your_password'
        }
    });
    
    

    Here, we configure our mailman with our Gmail account information. We give him our email address and password so he can access our mailbox and send messages for us.

  3. Prepare the email :

    let mailOptions = {
        from: '"Fred Foo 👻" <foo@example.com>', // Who sends the email
        to: 'ami1@example.com, ami2@example.com', // Who to send the email to
        subject: 'Hello ✔', // Email subject
        text: 'Hello world?', // Plain text or
        html: '<b>Hello world?</b>' // HTML content
    };
    
    

    We write our email. We define who's sending it (here, Fred Foo), who it's for (several friends), the subject (e.g. "Hello ✔"), and the content (a nice message in text or HTML).

  4. Send the email :

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    });
    
    

    Finally, we ask our digital letter carrier to send the e-mail. If there's a problem (for example, if the password is incorrect), we display the error. Otherwise, we indicate that the e-mail has been sent and even provide a link to view the e-mail sent (handy for checking).

💡 Never put your password in plain text in your code! Use environment variables or password management services to keep your information safe.

Basically, it's like asking a trusted mailman to send an e-mail using your Gmail account.


Now you need to be able to send emails anywhere in the world. If you have any questions, don't hesitate to ask. Happy coding ✨

Top comments (0)