Search

Nodejs Send Email with Attachment Tutorial

post-title

We will share with you in this article how to send an email with a file attachment in nodeJs using nodemailer package. mail send functionality is very common in nodejs application and you can be done using nodemailer. this is one of the best packages for work with mail sending in node js application.

What is nodemailer

Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default.

Before you can start or implement this code in your local system nodeJs must be installed in your system.

If you never use before nodemailer in your nodejs application then don't worry we will here share with you all step by step. here we also have seen you how to configure Gmail mail setting in your nodemailer and how to send mail using your own Gmail account.

Step - 1 Install Package

First things we need to install a package in our nodejs application. first create one empty folder mailsenddemo for nodejs application. then go to your nodejs project root path and run npm init command for creating pakcage.json a file. then running the following command for install nodemailer package in your nodejs application.

npm install nodemailer

Make sure if you want to use the latest nodemailer package in your nodejs application then you installed nodejs version must be node.Js v6.0.0

Step - 2 Create index.js file

Now, we need to create one index.js file in your project root directory. and write the following code into it.

'use strict';
const nodemailer = require('nodemailer');

// async..await is not allowed in global scope, must use a wrapper
async function main() {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    let testAccount = await nodemailer.createTestAccount();

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: testAccount.user, // generated ethereal user
            pass: testAccount.pass // generated ethereal password
        }
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
        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
    });

    console.log('Message sent: %s', info.messageId);
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);

After doing this code in your index.js file and change your receivers and sender email id then run the following command in your terminal for a run this index.js file and check your code worked or not.

node index.js

After hitting the above command in your terminal then you can see the following output in your terminal.

Message sent: <2f114f67-a092-a291-d12b-f43ce795c883@gmail.com>
Preview URL: https://ethereal.email/message/Xaaj7HdneCuitgEMXaaj7wzb8CwPgbMbAAAAAYhvQhZDopLUBKHrXi7fzOg

Then copy the Preview URL and open it in a new tab in your browser window. then you can see your sending mail content preview like that see the following image.

Gmail Configuration

If you want to use Gmail SMTP for send mail. and then that mail you want to send on your real Gmail account then do the following step.

Just change the following code for the Gmail SMTP configuration.

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false, // true for 465, false for other portss
    auth: {
        user: 'yourgmail@gmail.com', // generated ethereal user
        pass: 'your email account password' // generated ethereal password
    }
});

Enable Less Secure Apps

We also need to unable lesssecureapps functionality in your google Gmail account which you want to set in SMTP. just click on this link and enabled it Google Account Less Secure Apps Enable

Then run your nodejs application again by running the following command.

node index.js

After running your index.js the file then now output will be the following in the terminal.

Message sent: <058d5c5b-d72e-4e55-8008-5aa861d07334@gmail.com>
Preview URL: false

Here Preview URL is false so that mail content send on your gmail account. once check and confirm.

Conclusion

As you can see, how to send mail in node js with file attachment using nodemailer package is it very easy to implement in your node js application

We hope that small tutorials help everyone.