How to SendGrid send email with node from terminal

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.

Commands:

$ 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')

mailer.setApiKey('YourSendGridKey');

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: `${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 following command from your terminal

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

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status