DEV Community

Abdulhafeez Abdulraheem
Abdulhafeez Abdulraheem

Posted on • Originally published at on

Sending Mails with Sendgrid and Node.js

Essentially in every web application, there's a need to send the user an email. In this article, I would love to show you how easy it is to setup Sendgrid and send emails easily to users. We will set up an easy module that will handle our mail sending.

Image result for nodejs

Installing SendGrid

Firstly, we need the official package for sending emails. Run the following command :

npm install @sendgrid/mail
Enter fullscreen mode Exit fullscreen mode

Now we have the Sendgrid node package for the sending emails in your node application.

To use this package you need an API key which you will get here after you must have created an account.

Configuring Sendgrid

In my application, I like to create the email sending module in a separate file in a utils folder and name it emails.js

// emails.js

const SGmail = require('@sendgrid/mail')

SGmail.setApikey('xxxxx-xxxxx') // Input Api key or add to environment config
Enter fullscreen mode Exit fullscreen mode

I strongly advise you don’t hardcode your API key, use an environment variable instead, check out this awesome post to get started if you don’t know how to use config vars in node.js

Mail Sending

Let’s create a simple function to send the email


function newUserEmail(email, name){

const message = {

to : email, //email variable

from : { email : 'your email' , name: 'Name of user you want to send email as'},

message : `Hi there, ${name}`,

subject : "This is a test Email"


SGmail.send(message).then((sent) =\> {

// Awesome Logic to check if mail was sent



module.exports = {

Enter fullscreen mode Exit fullscreen mode

Let me explain each of the keys and values in the message object created above

⦁ to: The recipient’s email.

⦁ from: the from object contains the email key which would be used as the sender email and name which would be used as the sender name.

⦁ message: which is the content of your email. You can also use HTML tags, in which case the key wouldn’t be message, but html instead.

⦁ subject: The email subject.


I am sure you see how easy it is to send emails with Sendgrid. This can save a lot of development time and debugging time with minimal configurations. Now you can import the function anywhere in your code and send a mail, easy!

Reach out to me via and give me a follow on twitter.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast , 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

Top comments (1)

tateronaut profile image
tate shepherd • Edited

Hey Thanks for this article! Exactly what I was looking for. Just a tip, you can add syntax highlighting to your code snippets, which are helpful in my opinion. With the markdown editor you just write the language name after the first set of three backticks. In this case "javascript"