Skip to content

How to SendGrid send email with node from terminal

Last updated on November 21, 2022

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

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

Commands:

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

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

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

mailer.setApiKey('YourSendGridKey');

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

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

    const msg = {
      to: 'to@emailAddress',
      from: 'from@emailAddress',
      subject: 'Weekly Scan Report',
      html: `${data}`
    };

  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 follow the command from your terminal

$ npm emailTrigger.js path/to/file.txt
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments