Posted by Arjun on Thursday 20th September 2018

How to SendGrid send email with node from terminal

How to

In this post, I am gonna share code snippets which will trigger email along with file content to the given email address usign SendGrid and it will run on top of node js.

Create a folder called emailTrigger and issue npm init --yes, it will create a file called packagejson file. Now install @sendgrid/mail library with npm install @sendgrid/mail.


$ mkdiar emailTrigger
$ cd emailTrigger
$ npm init --yes
$ npm install @sendgrid/mail

Now create a file emailTrigger.js along with below code.

const mailer = require('@sendgrid/mail');
const fs = require('fs')


var myArgs = process.argv.slice(2); 

const data = fs.readFileSync(myArgs[0])

    const msg = {
      to: '[email protected]',
      from: '[email protected]',
      subject: 'Weekly Scan Report',
      html: `<html><head></head><body>${data}</body></html>`

  mailer.send(msg).then(data => console.log(data)).catch(error => console.log(error));    

In order to trigger email along with the given file content issue following command from your terminal

$ npm emailTrigger.js path/to/file.txt