Skip to main content
nodejs-sendgrid-example

Sendgrid Nodejs Example Using ExpressJS

This nodejs tutorial help to send mail using sendgrid and nodejs express server.The sendgrid is the most popular mail service provider and nodejs is popular framework for web application.I am using expressjs framework to create API into this nodejs application.

I have already shared How To Send Email Using Nodemailer.

I will create rest api that will send email with hello message to the target emailId. Create new route with HTTP get method and UI will call this endpoint to send mail.

The sendgrid is providing the nodejs libs to send mail. This is a dedicated service for interaction with the mail endpoint of the Sendgrid v3 API. You need APIKEY to access sendgrid api functionality and send mail.You can get APIKEY by sign up SendGrid account for free, You can send up to 40,000 emails for the first 30 days.

Please don’t hard-code APIKey, instead of use an environment variable or some other secure means of protecting your Twilio SendGrid API Key.

How To Send Mail Using SendGrid

Created ‘test-mail’ folder in any location of the computer, Let’s create below files into this folder –

  • package.json : This file contains all package information or dependencies.
  • main.js : This file contains express server and app functionality.

Install Nodejs Dependencies

The package.json file is responsible to install all dependencies of nodejs application. Open test-mail/package.json file and added below code into this file –

{
  "name": "node-restapi",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": {
    "name": "Adam",
    "email": "[email protected]",
    "url": "http://js-tutorials.com/"
  },
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.16.1",
    "cors": "^2.8.5",
    "express": "^4.14.1",
    "@sendgrid/mail": "^6.5.1"
  }
}

The body-parser is middleware that extract the entire body portion of an incoming request stream and exposes it on req.body.
The cors is a middleware that can be used to enable CORS with various options.
The express is nodejs rest api framework.
The sendgrid/mail is a nodejs package to send mail.

Now open command line and run below command to install dependencies –
/test-mail$ npm install

How to Create Express Server in Nodejs

Let’s open main.js file added below code into this file –

var express = require('express')
  , path = require('path')
  , app = express()
  ,cors = require('cors')
  ,sgMail = require('@sendgrid/mail');

sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Testing mail with SendGrid using nodejs',
  text: 'test text',
  html: 'Its too simple to send mail',
};

app.use(cors());
const PORT = process.env.PORT || 3010;
app.set('port', process.env.PORT || 3010);
app.use(express.static(path.join(__dirname, 'public')));
 app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});
app.get('/sendmail',(req, res) => {

  sgMail.send(msg);
  res.send('Successfully! Sent mail');
});

I have created express server and run into 3010 port.We’re using Express’s get method to create express route to send mail. You can send mail using route /sendmail, I have added both params request and response which by convention are shortened to req and res. The first params represent the request object and the second one the response object.

Leave a Reply

Your email address will not be published. Required fields are marked *