The Startup
Published in

The Startup

How to Send CSV Files With Nodemailer

Well, there has been a slight struggle on how to send CSV file as an attachment using Node.js. If you’re wondering how to do that, look no further, we are going to do just that in this post! 😊

We will dwell into using Nodemailer, a popular emailing module that literally makes sending makes “easy as cake”. It is a project that was started back in 2010 and now is a “de facto” solution for emailing that Node.js developers turn to.

Well, there has been a slight struggle on how to send CSV file as an attachment using Node.js. If you’re wondering how to do that, look no further, we are going to do just that in this post! 😊

We will dwell into using Nodemailer , a popular emailing module that literally makes sending makes “easy as cake”. It is a project that was started back in 2010 and now is a “de facto” solution for emailing that Node.js developers turn to.

Setup a workspace

Let’s get started by creating a new npm repository using your preferred terminal.

npm init --y

Note: That --y flag is for people that don’t have much time 😛.

Install dependencies

We will install the following dependencies in our repository:

  • Nodemailer
  • json2csv

Yet again, let’s use your preferred terminal and the npm package manager to install the dependencies:

npm i --save nodemailer json2csv

If you’re successful, your package.json should list the dependencies with the “latest” version number against each of them.

json2csv module is used to convert JSON objects to CSV format in an easy and neat manner.

Write some boilerplate code

Now let’s include the Nodemailer dependency into our code and initialize a transporter. Note that I’m using the ES6 syntax for the code.

const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "<email>",
pass: "<password>",
},
});

In the above example, we have Ethereal email service. Ethereal is a fake SMTP service, mostly aimed at Nodemailer users (but not limited to). It’s a completely free anti-transactional email service where messages never get delivered.

Now, let’s initialize some random JSON data.

const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "<email>",
pass: "<password>",
},
});
//some data
const data = [{relation:"father",name:"Anakin Skywalker"},{relation:"son",name:"Luke Skywalker"}];

Let’s convert the data into CSV using the light but awesome csvtojson library

const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "<email>",
pass: "<password>",
},
});
//some data
const data = [{relation:"father",name:"Anakin Skywalker"},{relation:"son",name:"Luke Skywalker"},...];
//conver the data to CSV with the column names
const csv = parse(data, ["relation","name"]);

Now, without further ado, let’s send this data as a CSV attachment leveraging the Nodemailer transporter mail options. Note that the data is sent using the “attachments” key on the mail configuration.

transporter.sendMail(
{
from: "darth.vader@sithmail.com",
to: "luke.skywalker@jedimail.com",
subject: "You need to know the truth",
text: "Ola! Please check the attachment for a surprise 😊",
html: "<b>Ola! Please check the attachment for a surprise! 😊</b>",
// here is the magic
attachments: [
{
filename: "file.csv",
content: csv,
},
],
},
(err, info) => {
if (err) {
console.log("Error occurred. " + err.message);
return process.exit(1);
}
console.log("Message sent: %s", info.messageId);
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
);

Let’s complete our example

const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
auth: {
user: "<email>",
pass: "<password>",
},
});
//some data
const data = [
{ relation: "father", name: "Anakin Skywalker" },
{ relation: "son", name: "Luke Skywalker" },
];
//conver the data to CSV with the column names
const csv = parse(data, ["relation", "name"]);
transporter.sendMail(
{
from: "darth.vader@sithmail.com",
to: "luke.skywalker@jedimail.com",
subject: "You need to know the truth",
text: "Ola! Please check the attachment for a surprise 😊",
html: "<b>Ola! Please check the attachment for a surprise! 😊</b>",
//here is the magic
attachments: [
{
filename: "file.csv",
content: csv,
},
],
},
(err, info) => {
if (err) {
console.log("Error occurred. " + err.message);
return process.exit(1);
}
console.log("Message sent: %s", info.messageId);
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
);

You should now receive an email on the receiver mailbox with the attached CSV file with the appropriate data! Boom! you’re done!

Read more at Grizzlybit 🐻.

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Build a Twilio-Powered Chat App Using React Native

https://youtu.be/k0Mtq4mNOUo

How to compile a string using Laravel Blade

JS: Writing Async/Await with Generators

Does React.Context Replace Redux?

Top 20 JavaScript tips and tricks to increase your Speed and Efficiency

Google OAuth using Passport.js: How to get started

Strapi: How to create a service to manage help documents?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Zubair Ahmed

Zubair Ahmed

Chief Technology Officer at RAZRLAB

More from Medium

Scheduled Cron Jobs with Render

Deploy React App on GitHub Pages Automatically

How to Convert an Audio File into Video in NodeJS

Node.js: Export JSON Data to Excel Easily

Node.js: Export JSON Data to Excel Easily