Home » Node.js

How to send emails with attachments using Nodemailer | Node.js

Sending emails using Nodemailer: Here, we are going to learn how to send emails with attachments using Nodemailer in Node.js?
Submitted by Godwill Tetah, on September 12, 2019

In the previous article, "How to send emails using Nodemailer?", we discussed how to send simple emails using Nodemailer in Node.js? Here, we are going to learn further – How to send emails with attachments using Nodemailer in Node.js?

Here is the code to send emails with attachments using Nodemailer,

// load the node mailer module
var nodemailer = require('nodemailer');    

//configure the transporter

var transporter = nodemailer.createTransport({    
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'your gmail password'
  }
});

//email  options

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email using Node.js',
  text: 'sending email with attchments',

// attachment.
// you can use the same format and send as many attachments as possible

attachments: [        
        {   
          filename: 'textfile.txt',
            path: 'C:/Users/GODWILL TETAH/Downloads/textfile.txt'
        }
]
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent');
  }
});

To add attachment from a cloud storage system online, you can use the URL,

{   
	// use URL as an attachment
	filename: 'license.txt',
	path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE'
},

Note: You can use the same format and send as many attachments as possible. Make sure the closing curly bracket of each attachment is separated by a comma sign (,).

Finally, start your node app and if sending is successful, the phrase ‘email sent' will be printed out on the console or terminal.

Check you're the email's inbox.

Using Gmail as your transporter, you can also enable the less secure app access setting.

Nodemailer 1

Sending email requires internet connection.

Do not fear about your password security. It's a tested and secured module used by many since 2010.

Also, don't forget the comma sign (,) that kind of separates the text content and the attachment.

It gave me some hard time when preparing this article.

Nodemailer 2

Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.