> ## Documentation Index
> Fetch the complete documentation index at: https://docs.comify.io/llms.txt
> Use this file to discover all available pages before exploring further.

# SendGrid

> Learn how to send emails via SendGrid using Comify.

The SendGrid provider enables you to deliver professional transactional emails to your customers through the Comify Platform. With a single API integration, you can create seamless multi-channel communication experiences.

## Getting Started

Implementing the SendGrid email provider requires three primary steps: creating a SendGrid account, generating a SendGrid API key, and configuring the SendGrid integration within your Comify platform.

## Creating a SendGrid Account

Follow these steps to set up your SendGrid account:

1. Visit [SendGrid's official website](https://sendgrid.com/) and select "Start for Free".
2. Enter all required information to create your account. Note that this user will serve as the primary SendGrid account administrator.
3. Complete the security verification process for both your email address and phone number.
4. Store the provided Recovery Code in a secure location for account recovery purposes.
5. Once verification is complete, select "Create new account" to proceed with your initial login and finalize your account setup.
6. Use the SendGrid setup wizard to configure your sender identities. Access this guide at [app.sendgrid.com/guide](https://app.sendgrid.com/guide).

## Creating a SendGrid API Key

Follow these steps to generate and secure your SendGrid API key:

1. In your SendGrid dashboard, navigate to Settings in the left sidebar, then select API Keys.
2. Click the Create API Key button.
3. Assign a descriptive name to your key (e.g., "Comify Integration") for easy identification.
4. Select the appropriate access level. For enhanced security, we recommend using Restricted Access with only the minimum permissions necessary.
5. When using Restricted Access, carefully select only the specific permissions required for email delivery functionality.
6. Click Create & View to generate your key.
7. Immediately copy and securely store your API key. Important: For security purposes, SendGrid displays this key only once.

## Creating a Comify API Key

Before configuring the SendGrid integration, you'll need to generate a Comify API key for authentication:

1. Access your Comify account dashboard.
2. Navigate to the API Keys management section at [https://cloud.comify.io/settings/api-keys](https://cloud.comify.io/settings/api-keys).
3. Select "Generate API Key" if not already generated.
4. Provide a clear, descriptive name for your key (e.g., "SendGrid Integration") to facilitate future management.
5. Copy and store this API key in a secure location. You'll use this key in your application code to authenticate requests to the Comify platform.

## Configuring SendGrid Integration in Comify

To establish the connection between Comify and SendGrid:

1. Sign in to your Comify platform dashboard.
2. Navigate to Integration Store > Add Integration > E-mail.
3. From the available email service providers, select SendGrid.
4. Enter the SendGrid API key you generated earlier.
5. Configure any additional provider-specific settings according to your requirements.
6. Click Save to finalize the integration.

![SendGrid Comify Integration](https://ik.imagekit.io/flaberry/transify-waba/comify-docs/channels/sendgrid-comify-integration.png)

## Creating Email Templates

After successfully configuring the SendGrid integration, you can design email templates directly within the Comify platform:

1. Navigate to the [Manage Templates](https://cloud.comify.io/templates/manage) section in your Comify dashboard.
2. Select the `Email` tab from the available channel options.
3. Click `Create Template` to begin the design process.
4. Choose from multiple template creation methods based on your preference and skill level:
   * **AI-Assisted Design**: Utilize the `AI Writer` feature in the Email Editor section for automated content generation.
   * **Manual HTML Editing**: Select `Switch to HTML` in the Email Editor for direct code editing.
   * **Import Existing Templates**: Use the Chrome extension to copy HTML from existing templates for reuse in Comify.

## Sending Email Templates

Implement the following code examples in your application to trigger email template delivery:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const { Comify } = require('comify-node')

    const comm = new Comify('COMIFY_API_KEY')

    comm.triggerComm('email_template_name',{ 
      "order_id" : "123455",
      "billing" : {
        "customerEmail" : "contact@comify.io",
        "customerName" : "Comify"
      }
    }, 'email')
    ```
  </Tab>

  <Tab title="Node.js (Fetch)">
    ```javascript theme={null}
    const fetch = require('node-fetch');

    const apiKey = 'YOUR_COMIFY_API_KEY';
    const url = 'https://commify.transify.tech/v1/comm';

    const payload = {
      name: 'email_template_name',
      payload: { 
        order_id: '123455',
        billing: {
          customerEmail: 'contact@comify.io',
          customerName: 'Comify'
        }
      },
      type: 'email'
    };

    fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `ApiKey ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    api_key = 'YOUR_COMIFY_API_KEY'
    url = 'https://commify.transify.tech/v1/comm'

    headers = {
        'Authorization': f'ApiKey {api_key}',
        'Content-Type': 'application/json'
    }

    payload = {
        'name': 'email_template_name',
        'payload': {
            'order_id': '123455',
            'billing': {
                'customerEmail': 'contact@comify.io',
                'customerName': 'Comify'
            }
        },
        'type': 'email'
    }

    response = requests.post(url, headers=headers, json=payload)
    print(response.json())
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    require 'net/http'
    require 'uri'
    require 'json'

    api_key = 'YOUR_COMIFY_API_KEY'
    url = URI.parse('https://commify.transify.tech/v1/comm')

    payload = {
      name: 'email_template_name',
      payload: {
        order_id: '123455',
        billing: {
          customerEmail: 'contact@comify.io',
          customerName: 'Comify'
        }
      },
      type: 'email'
    }

    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(url.request_uri)
    request['Authorization'] = "ApiKey #{api_key}"
    request['Content-Type'] = 'application/json'
    request.body = payload.to_json

    response = http.request(request)
    puts response.body
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
    $api_key = 'YOUR_COMIFY_API_KEY';
    $url = 'https://commify.transify.tech/v1/comm';

    $payload = [
        'name' => 'email_template_name',
        'payload' => [
            'order_id' => '123455',
            'billing' => [
                'customerEmail' => 'contact@comify.io',
                'customerName' => 'Comify'
            ]
        ],
        'type' => 'email'
    ];

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: ApiKey ' . $api_key,
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    echo $response;
    ?>
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
    )

    func main() {
        apiKey := "YOUR_COMIFY_API_KEY"
        url := "https://commify.transify.tech/v1/comm"
        
        type Billing struct {
            CustomerEmail string `json:"customerEmail"`
            CustomerName  string `json:"customerName"`
        }
        
        type PayloadData struct {
            OrderID string  `json:"order_id"`
            Billing Billing `json:"billing"`
        }
        
        type RequestBody struct {
            Name    string      `json:"name"`
            Payload PayloadData `json:"payload"`
            Type    string      `json:"type"`
        }
        
        data := RequestBody{
            Name: "email_template_name",
            Payload: PayloadData{
                OrderID: "123455",
                Billing: Billing{
                    CustomerEmail: "contact@comify.io",
                    CustomerName:  "Comify",
                },
            },
            Type: "email",
        }
        
        jsonData, err := json.Marshal(data)
        if err != nil {
            fmt.Println("Error marshalling JSON:", err)
            return
        }
        
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
        if err != nil {
            fmt.Println("Error creating request:", err)
            return
        }
        
        req.Header.Set("Authorization", "ApiKey "+apiKey)
        req.Header.Set("Content-Type", "application/json")
        
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            fmt.Println("Error sending request:", err)
            return
        }
        defer resp.Body.Close()
        
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Println("Error reading response:", err)
            return
        }
        
        fmt.Println(string(body))
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import java.util.Scanner;

    public class ComifySendEmail {
        public static void main(String[] args) {
            try {
                String apiKey = "YOUR_COMIFY_API_KEY";
                URL url = new URL("https://commify.transify.tech/v1/comm");
                
                String jsonPayload = "{"
                    + "\"name\": \"email_template_name\","
                    + "\"payload\": {"
                    + "    \"order_id\": \"123455\","
                    + "    \"billing\": {"
                    + "        \"customerEmail\": \"contact@comify.io\","
                    + "        \"customerName\": \"Comify\""
                    + "    }"
                    + "},"
                    + "\"type\": \"email\""
                    + "}";
                
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Authorization", "ApiKey " + apiKey);
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);
                
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                
                int responseCode = connection.getResponseCode();
                System.out.println("Response Code: " + responseCode);
                
                try (Scanner scanner = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name())) {
                    String responseBody = scanner.useDelimiter("\\A").next();
                    System.out.println(responseBody);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    ```
  </Tab>

  <Tab title="Curl">
    ```bash theme={null}
    curl -X POST 'https://commify.transify.tech/v1/comm' \
      -H 'Authorization: ApiKey YOUR_COMIFY_API_KEY' \
      -H 'Content-Type: application/json' \
      -d '{
        "name": "email_template_name",
        "payload": {
          "order_id": "123455",
          "billing": {
            "customerEmail": "contact@comify.io",
            "customerName": "Comify"
          }
        },
        "type": "email"
      }'
    ```
  </Tab>
</Tabs>

Upon successful API request processing, you will receive a response containing a unique requestId and confirmation message:

```json theme={null}
{
  "requestId": "016e9d9c-ea29-455c-bf2e-a703e96482fb",
  "message": "your request has been submitted"
}
```

Important: The API may return a success response even when there are underlying issues with your request. For comprehensive delivery monitoring and troubleshooting, we recommend reviewing the complete request logs in the [Activity Feed](https://cloud.comify.io/monitor/activity) dashboard.
