> For the complete documentation index, see [llms.txt](https://kasplo.gitbook.io/kasplo-doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kasplo.gitbook.io/kasplo-doc/channels/email-api/send-via-api/code-samples.md). Agents can also search and read this documentation through its [MCP server](https://kasplo.gitbook.io/kasplo-doc/~gitbook/mcp).

# Code Samples

Production-ready integration snippets in popular programming languages to send email via the **Kasplo Email API**.

***

## Endpoint & Authentication

* **Endpoint**: `https://api.kasplo.com/v1/send-email`
* **HTTP Method**: `POST`
* **Header**: `api-key: <KASPLO_API_KEY>` or `Authorization: Bearer <KASPLO_API_KEY>`
* **Content-Type**: `application/json`

Store your API key in an environment variable (`KASPLO_API_KEY`) and avoid hardcoding credentials in your application repository.

***

{% tabs %}
{% tab title="cURL" %}

```bash
curl --request POST "https://api.kasplo.com/v1/send-email" \
  --header "api-key: $KASPLO_API_KEY" \
  --header "Content-Type: application/json" \
  --data-raw '{
    "email": {
      "from": "sender@yourdomain.com",
      "fromName": "Your Company",
      "subject": "Hello from Kasplo",
      "text": "Hello! This email was sent using the Kasplo Email API.",
      "html": "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
      "recipients": {
        "to": [
          {
            "name": "Alex",
            "email": "recipient@example.com"
          }
        ]
      }
    }
  }'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const apiKey = process.env.KASPLO_API_KEY;

async function sendEmail() {
  const payload = {
    email: {
      from: "sender@yourdomain.com",
      fromName: "Your Company",
      subject: "Hello from Kasplo",
      text: "Hello! This email was sent using the Kasplo Email API.",
      html: "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
      recipients: {
        to: [
          {
            name: "Alex",
            email: "recipient@example.com"
          }
        ]
      }
    }
  };

  const response = await fetch("https://api.kasplo.com/v1/send-email", {
    method: "POST",
    headers: {
      "api-key": apiKey,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  });

  const data = await response.json();

  if (!response.ok) {
    throw new Error(`Kasplo API error: ${JSON.stringify(data)}`);
  }

  console.log("Success:", data);
}

sendEmail().catch(console.error);
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

api_key = os.environ.get("KASPLO_API_KEY")

url = "https://api.kasplo.com/v1/send-email"

headers = {
    "api-key": api_key,
    "Content-Type": "application/json"
}

payload = {
    "email": {
        "from": "sender@yourdomain.com",
        "fromName": "Your Company",
        "subject": "Hello from Kasplo",
        "text": "Hello! This email was sent using the Kasplo Email API.",
        "html": "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
        "recipients": {
            "to": [
                {
                    "name": "Alex",
                    "email": "recipient@example.com"
                }
            ]
        }
    }
}

response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()

print("Success:", response.json())
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$apiKey = getenv("KASPLO_API_KEY");
$url = "https://api.kasplo.com/v1/send-email";

$payload = [
    "email" => [
        "from" => "sender@yourdomain.com",
        "fromName" => "Your Company",
        "subject" => "Hello from Kasplo",
        "text" => "Hello! This email was sent using the Kasplo Email API.",
        "html" => "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
        "recipients" => [
            "to" => [
                [
                    "name" => "Alex",
                    "email" => "recipient@example.com"
                ]
            ]
        ]
    ]
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "api-key: " . $apiKey,
        "Content-Type: application/json"
    ],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

$response = curl_exec($ch);

if ($response === false) {
    throw new Exception("cURL Error: " . curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    throw new Exception("Request failed with HTTP {$httpCode}: {$response}");
}

echo "Success: " . $response . "\n";
```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class KasploSendEmail {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("KASPLO_API_KEY");

        String payload = """
        {
          "email": {
            "from": "sender@yourdomain.com",
            "fromName": "Your Company",
            "subject": "Hello from Kasplo",
            "text": "Hello! This email was sent using the Kasplo Email API.",
            "html": "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
            "recipients": {
              "to": [
                {
                  "name": "Alex",
                  "email": "recipient@example.com"
                }
              ]
            }
          }
        }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.kasplo.com/v1/send-email"))
                .header("api-key", apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() >= 400) {
            throw new RuntimeException("Request failed [" + response.statusCode() + "]: " + response.body());
        }

        System.out.println("Success: " + response.body());
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

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

func main() {
	apiKey := os.Getenv("KASPLO_API_KEY")

	payload := map[string]interface{}{
		"email": map[string]interface{}{
			"from":     "sender@yourdomain.com",
			"fromName": "Your Company",
			"subject":  "Hello from Kasplo",
			"text":     "Hello! This email was sent using the Kasplo Email API.",
			"html":     "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
			"recipients": map[string]interface{}{
				"to": []map[string]string{
					{
						"name":  "Alex",
						"email": "recipient@example.com",
					},
				},
			},
		},
	}

	body, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest(http.MethodPost, "https://api.kasplo.com/v1/send-email", bytes.NewBuffer(body))
	if err != nil {
		panic(err)
	}

	req.Header.Set("api-key", apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	if resp.StatusCode >= 400 {
		panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, respBody))
	}

	fmt.Println("Success:", string(respBody))
}
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require "net/http"
require "json"
require "uri"

api_key = ENV.fetch("KASPLO_API_KEY")
uri = URI("https://api.kasplo.com/v1/send-email")

payload = {
  email: {
    from: "sender@yourdomain.com",
    fromName: "Your Company",
    subject: "Hello from Kasplo",
    text: "Hello! This email was sent using the Kasplo Email API.",
    html: "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
    recipients: {
      to: [
        {
          name: "Alex",
          email: "recipient@example.com"
        }
      ]
    }
  }
}

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

request = Net::HTTP::Post.new(uri)
request["api-key"] = api_key
request["Content-Type"] = "application/json"
request.body = JSON.generate(payload)

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed with code #{response.code}: #{response.body}"
end

puts "Success: #{response.body}"
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string apiKey = Environment.GetEnvironmentVariable("KASPLO_API_KEY")
            ?? throw new Exception("KASPLO_API_KEY environment variable is not set.");

        const string url = "https://api.kasplo.com/v1/send-email";

        const string payload = """
        {
          "email": {
            "from": "sender@yourdomain.com",
            "fromName": "Your Company",
            "subject": "Hello from Kasplo",
            "text": "Hello! This email was sent using the Kasplo Email API.",
            "html": "<h2>Hello!</h2><p>This email was sent using the <strong>Kasplo Email API</strong>.</p>",
            "recipients": {
              "to": [
                {
                  "name": "Alex",
                  "email": "recipient@example.com"
                }
              ]
            }
          }
        }
        """;

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("api-key", apiKey);

        using var content = new StringContent(payload, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);

        string responseBody = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with status {response.StatusCode}: {responseBody}");
        }

        Console.WriteLine($"Success: {responseBody}");
    }
}
```

{% endtab %}
{% endtabs %}

***

## Next Steps

* For grouped recipients (`toList`), CC, BCC, attachments, scheduling, and metadata, see [API Options](https://kasplo.gitbook.io/kasplo-doc/channels/email-api/send-via-api/api-options.md).
* For status codes and retry handling, see [API Responses & Errors](https://kasplo.gitbook.io/kasplo-doc/channels/email-api/send-via-api/api-responses-and-errors.md).
