Send Mails Programmatically with Sendgrid
Tags: javascript, nextjs, webdev, react
Published: 2021-08-22 06:36:27

Giving a little bit of background, I am working as an intern and was asked to build a portal that would send a bunch of emails at once.<br> 
And honestly, I had no idea how to do it. One of my teammates suggested looking into SendGrid.
I've spent quite some time learning and debugging & so thought of sharing my knowledge through this article. Hope this saves you some frustration and time.

In this article, we'll learn how to send email via SendGrid step-by-step through our NextJs Application. <br>
PS: You'll be able to follow, even if you haven't worked on NextJs.

So without wasting any time
 let's jump right into it.

1. ## Creating a SendGrid Account:
 - **Signup:**  
    Certainly, the first step would be to signup. Enter email & password and let's quickly move onto the next step
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629470343731/IB15fm2r5.png)
<hr>
   - **Fill in details:** <br>
      In this step, SendGrid requires us to fill in some primary details.
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629471969954/_ZNMwedyH.png)
<hr>
   - **Domain VS Single Sender Authentication:**
      After completing basic registration steps and confirming your email you would see this screen

      If you have a **domain** want to send emails through your **domain** then go ahead and 
      Click on **Domain Authentication** and complete the necessary steps. <br>
      Or else Click on **Single Sender Verification** and let's look into the sender's verification in 
      our next step.
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629478820162/z0f6LgUlX.png)
<hr>
   - **Single Sender Verification:** <br>
      The Process is pretty straight forward but here are few fields to understand:
      - **From Name**: This name would appear as the sender's name.
      - **From Email Address**: We will use this address to send emails.
      - **Reply To**: This email address will receive all the replies. 

     Note: **From Email Address** & **Reply To** can be the same email address as well.
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629554518179/XEL6b262q.png)
<hr>
    - **API KEY:**
       Now, it's time to get our API KEY. <br>
       Go to **Settings > API Keys** & Click on **Create API Key**.
       
       Select **Full Access**, Name your **Key** anything you want, this name for your reference 
       and has nothing to do with our code ahead.
       
      **Make sure you maintain a copy of the API Key somewhere, as SendGrid won't let us access 
       the API key again.**
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629483147759/OVCYhk2-2.png)
<hr>
     - **Dynamic Template:**
        So, this is one of the most interesting parts, creating our own custom beautiful template. 
        Let's send professional templated emails. <br>
        Navigate to **Email API > Dynamic Templates**, Click on **Create a Dynamic Template** 
        enter any name of your choice (I have named it *demo*).

        Your screen should look like this 👇
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629532083530/Xj4GDAWTU.png)
        
         Here you'll see **Template-ID**, we will need this later in our code.

         Click on **Add Version > Blank Template > Code Editor** (Refer to the GIF below) <br>
         I usually prefer designing a template from scratch, but you can select **Sendgrid Email 
         Design** for some pre-designed templates and then edit in the code-editor environment.

        *Tip: You'll also find many pre-designed templates on the internet.*
<a href="https://www.loom.com/share/091a69894fe340c19fe1359da895021b">
    <p>SendGrid Demo | Hashnode Blog - Watch Video</p>
    <img style="max-width:300px;" src="https://cdn.loom.com/sessions/thumbnails/091a69894fe340c19fe1359da895021b-with-play.gif">
  </a>
         
    **Let's look into Dynamic Variables:**
          Notice how **username** is wraped into `{{ }}` --> `{{username}}`. 
          These are called **Dynamic Variables/Iterators**. These variable are not static and changes from mail-to-mail. 
          So, when we are coding we must take care of these dynamic variables.
          We will talk about this more, later in the article.
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629488001538/LdX67ECcv.png)
<hr>
That's it for the **SendGrid Account** Part. <br>
Now let's write some code and see the magic to happen.

2. ## Let's get into coding:
 Firstly,  let's create a file and name it `mail.js`. <br>
 PS: I have this file in my **utils ** folder.


 - **Setting up the sendgrid API Key:**
  To be able to send mails via SendGrid, we need to provide the **Sendgrid API Key** which we 
  kept aside initially.
  
  Here's how we do it 👇
 ```js
      const sgMail = require("@sendgrid/mail");
      sgMail.setApiKey(process.env.SendGrid_API);
 ```
 You should have your **Sendgrid API Key** in a **.env** file.
 Your **.env** file should look like this 👇
   ```js
       SendGrid_API = "YourApiKey"
   ```
   > Make sure your **SendGrid API Key** is not exposed or pushed to any version control 
      repository like (GitHub, Bitbucket, etc)

  SendGrid is quite conscious about security and exposing your **API Key** would result in 
  temporary suspension of your SendGrid account.

   <hr>

 - **The Logic for sending mails:**

    Firstly, let's take a look at the minimum needed code to send an email through SendGrid.
    ```js
      const msg = {
       to: 'recipient@example.com', // Change to your reciver's email
       from: 'youremail@example.com', //mail from which you want send mails
       subject: 'Lets learn to send mails programmatically ',
       text: 'Here goes your body content',
       html: '<strong>Can send temeplated mails too!</strong>', // optional
     }  
     sgMail
     .send(msg)
     .then(() => {
       console.log('Email sent')
      })
     .catch((error) => {
       console.error(error)
     })
   ```
   Now, let's understand the above code. <br>
   **SendGrid** requires us to pass an object, here it is named as `msg`

  The object should primarily contain:
  - `to` : Reciever's / Recipient's email address.
  - `from`: Your email or the email from which you want to send mails.
  - `subject`: The subject of your mail.
  -  `text`: The content of your mail.
  
  Then we invoke the `send` function provided by SendGrid and pass in the `msg` object.
  Then we chain it with `.then` & `.catch` as it returns a promise. <br>
  That's it! Run this file and see the mail land receiver's mailbox.

  You are done! But there's one shortcoming here. It is very difficult to add complexity or custom 
  functionality to the above code.

  Don't worry. We have a come around for the same.

<hr>
   
 - **Creating Email `class` :**
   So, we are creating a class named **Email**.  Even if we aren't coding in **Object Oriented 
  Programming** approach, constructing a class would help us achieve **reusability** and would 
  make things easier to handle. Also, it gets handy to add custom functionalities.

  Also, Now we are using an HTML/CSS template to make our email look impressive. 
  
  Here's how we do it 👇

   ```js
     export default class Email {
     constructor() {
       this.to = "recievers@gmail.com";
       this.name = "Reciever Name";
       this.fromEmail = "yourmail@gmail.com";
       this.fromName = "Your Name";
      }

      async sendMails() {
        const mailOptions = {
        to: this.to,
        from: {
          email: this.fromEmail,
          name: this.fromName,
          },
        templateId: "YourTemplateID", // Here goes your template-Id
        dynamic_template_data: {// dynamic data = which changes mail-to-mail
        username: this.name, // username would always be different     
      },
    };

     await sgMail.send(mailOptions).then(() => {
       console.log("Sent");
       }, console.error);
     }
  }
```
Here are few points to understand:
 - `templateId`: Put in your Template-Id here. SendGrid makes it extremely easy to send templated 
  emails. Simply put in the ID of the Template which you want to use. <br>
   
 - `dynamic_template_data`: This object contains dynamic content and iterators which have a 
    reference to the iterators in your templates.
   
<hr>
So here's how our `mail.js` should overall look 👇
```js
     const sgMail = require("@sendgrid/mail");
     sgMail.setApiKey(process.env.SendGrid_API);
     export default class Email {
     constructor(user) {
       this.to = "recievers@gmail.com";
       this.name = "Reciever Name";
       this.fromEmail = "yourmail@gmail.com";
       this.fromName = "Your Name";
      }

      async sendMails() {
        const mailOptions = {
        to: this.to,
        from: {
          email: this.fromEmail,
          name: this.fromName,
          },
        templateId: "YourTemplateID", // Here goes your template-Id
        dynamic_template_data: {// dynamic data = which changes mail-to-mail
        username: this.name, // username would always be different     
      },
    };

     await sgMail.send(mailOptions).then(() => {
       console.log("Sent");
       }, console.error);
     }
  }
``` 
<hr>
 - **Creating a `route`:**
    I have named my file `sendmails.js`, feel free to name it according to your preferences.
    
    ```js
       const router = express.Router();
       const Email = require("../utils/mail")

       router.post("/", async (req, res) => {
       try {
          await new Email().sendMails();
          res.status(200).json({
          message: "check your mail",
       });
       }catch (err) {
          console.log("err", err);
       }
      });

      module.exports = router;
  ```

  Let's go through the above code step-by-step.
  - Firstly, let's not forget to import our `Email Class` --> `const Email = require("../utils/mail")`
  - Now, let's write a `post` request.
  - Then we invoke the `.sendMails()` method on our `Email` Class.
  - And finally we send a json`message` with a `200` status.
  - Lastly, we add a `catch` block for logging errors if any.

<hr>

- **Making an `API Call`:**

   This is the last step, after this, you can start sending emails from your program/app!
   
   Now, we have everything in place and well set up. <br>
   We just need to make an API Call.
   
   Here's how we should do it 👇
   ```js
      async function sendMails() {
       try {
           const ress = await axios.post(`/api/sendmails`, {}));
        } catch {}
      }
   ```
   That's it. You are done! <br>
    Go check your inbox and take a look at your stunning templated mail.
<hr>

This is how we can send emails, but don't settle here. This is the simplest and the most straightforward way. <br>
I would recommend you to go ahead take a deep dive into [SendGrid Official Docs](https://docs.sendgrid.com/) and build amazing applications.

That's it from my side today. Let me know your thoughts in the comment section. <br>
If you liked the article give it a thumbs up. 

Hope you found value, and if you did consider supporting me [here](https://www.buymeacoffee.com/sayurikamble)