Send email with nodejs
Tags: backend, webdev, node, beginners
Published: 2024-07-06 01:22:26

## Prerequisites

- an e-mail address (to be used for sending e-mails)
- the package nodemail
    
    ```bash
    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](https://support.google.com/accounts/answer/185839?hl=en&co=GENIE.Platform%3DDesktop)

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 :

- Go to link : [https://myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords)
- Make sure you are logged in to your sender account
![Google app password plateform interface with red arrow to profile picture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5k60jk7znuspfxgngivb.png)

- Create a new application
![New application code creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6devn6dcpg45xlo5s9hr.png)

- Copy the supplied password
![Supplied password for the Test application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjon20eed5blnqm250ii.png)

> 💡 If the interface is empty, this means you haven't activated [2-factor authentication](https://support.google.com/accounts/answer/185839?hl=en&co=GENIE.Platform=Desktop)

## 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:

```jsx
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));
});

```

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

## Explanation

1. Import module :
    
    ```jsx
    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" :
    
    ```jsx
    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** :
    
    ```jsx
    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** :
    
    ```jsx
    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 ✨