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

# How to send email with AutoSend API

> Learn how to send emails using the AutoSend API with code examples in multiple programming languages.

Once you’ve created a transactional email template, you can use it in your application via the AutoSend API.

### API Endpoint

```jsx theme={null}
POST https://api.autosend.com/v1/mails/send
```

### Authentication

Include your API key in the Authorization header:

```jsx theme={null}
Authorization: Bearer YOUR_API_KEY
```

### Single Email with Template

**Request:**

<CodeGroup>
  ```bash cURL expandable theme={null}
  curl -X POST https://api.autosend.com/v1/mails/send \
   -H "Authorization: Bearer YOUR_API_KEY" \
   -H "Content-Type: application/json" \
   -d '{
  "to": {
  "email": "customer@example.com",
  "name": "Jane Doe"
  },
  "from": {
  "email": "hello@mail.yourdomain.com",
  "name": "Your Company"
  },
  "subject": "Welcome to Our Platform!",
  "html": "<h1>Welcome!</h1><p>Thanks for signing up.</p>"
  }'
  ```

  ```javascript NodeJS expandable theme={null}
  fetch("https://api.autosend.com/v1/mails/send", {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY", // Replace with your API key
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: {
        email: "no-reply@example.com",
        name: "AutoSend",
      },
      to: {
        email: "user@example.com",
        name: "Test User",
      },
      subject: "Welcome to AutoSend 🎉",

      // Option 1: Send using template
      templateId: "your_template_id",

      // Option 2: Send using raw HTML or text
      html: "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
      text: "Hello User, Thanks for joining AutoSend!",

      // Optional: Unsubscribe group for compliance
      unsubscribeGroupId: "12345",
    }),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(" Email sent successfully: ", data);
    })
    .catch((error) => {
      console.error("Error sending email:", error);
    });
  ```

  ```rust Rust expandable theme={null}
  use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
  use serde_json::json;
  use tokio;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      // API endpoint
      let url = "https://api.autosend.com/v1/mails/send";

      // Build request JSON payload
      let payload = json!({
          "from": {
              "email": "no-reply@example.com",
              "name": "AutoSend"
          },
          "to": {
              "email": "user@example.com",
              "name": "Test User"
          },
          "subject": "Welcome to AutoSend 🎉",
          // Option 1: template
          "templateId": "your_template_id",
          // Option 2: raw HTML / text
          "html": "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
          "text": "Hello User,
  Thanks for joining AutoSend!",
          // Optional: unsubscribe group
          "unsubscribeGroupId": "12345"
      });

      // Create HTTP client
      let client = reqwest::Client::new();

      // Send POST request
      let res = client
          .post(url)
          .header(AUTHORIZATION, "Bearer YOUR_API_KEY") // replace with your key
          .header(CONTENT_TYPE, "application/json")
          .json(&payload)
          .send()
          .await?;

      // Print response
      let status = res.status();
      let body = res.text().await?;
      println!("Status: {}", status);
      println!("Body: {}", body);

      Ok(())
  }
  ```

  ```go Go expandable theme={null}
  package main

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

  func main() {
  	url := "https://api.autosend.com/v1/mails/send"

  	// Build request body
  	payload := map[string]interface{}{
  		"from": map[string]string{
  			"email": "no-reply@example.com",
  			"name":  "AutoSend",
  		},
  		"to": map[string]string{
  			"email": "user@example.com",
  			"name":  "Test User",
  		},
  		"subject": "Welcome to AutoSend 🎉",

  		// Option 1: Send using template
  		"templateId": "your_template_id",

  		// Option 2: Send using raw HTML or text
  		"html": "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
  		"text": "Hello User,
  Thanks for joining AutoSend!",

  		// Optional: Unsubscribe group for compliance
  		"unsubscribeGroupId": "12345",
  	}

  	jsonData, err := json.Marshal(payload)
  	if err != nil {
  		fmt.Println("Error marshalling JSON:", err)
  		return
  	}

  	// Create request
  	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
  	if err != nil {
  		fmt.Println("Error creating request:", err)
  		return
  	}

  	req.Header.Set("Authorization", "Bearer YOUR_API_KEY") // Replace with real API key
  	req.Header.Set("Content-Type", "application/json")

  	// Send request
  	client := &http.Client{}
  	resp, err := client.Do(req)
  	if err != nil {
  		fmt.Println("Error sending request:", err)
  		return
  	}
  	defer resp.Body.Close()

  	// Read response
  	body, err := ioutil.ReadAll(resp.Body)
  	if err != nil {
  		fmt.Println("Error reading response:", err)
  		return
  	}

  	fmt.Println("Response status:", resp.Status)
  	fmt.Println("Response body:", string(body))
  }
  ```

  ```php PHP expandable theme={null}
  <?php

  $url = "https://api.autosend.com/v1/mails/send";

  $data = [
      "from" => [
          "email" => "no-reply@example.com",
          "name"  => "AutoSend"
      ],
      "to" => [
          "email" => "user@example.com",
          "name"  => "Test User"
      ],
      "subject" => "Welcome to AutoSend 🎉",

      // Option 1: Send using template
      "templateId" => "your_template_id",

      // Option 2: Send using raw HTML or text
      "html" => "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
      "text" => "Hello User,
  Thanks for joining AutoSend!",

      // Optional: Unsubscribe group for compliance
      "unsubscribeGroupId" => "12345"
  ];

  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer YOUR_API_KEY", // replace with your API key
      "Content-Type: application/json"
  ]);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

  $response = curl_exec($ch);

  if(curl_errno($ch)){
      echo "Curl error: " . curl_error($ch);
  } else {
      echo "Response: " . $response;
  }

  curl_close($ch);
  ```

  ```c# C# expandable theme={null}
  using System;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Text;
  using System.Threading.Tasks;
  using Newtonsoft.Json; // Install Newtonsoft.Json via NuGet

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://api.autosend.com/v1/mails/send";

          var payload = new
          {
              from = new { email = "no-reply@example.com", name = "AutoSend" },
              to = new { email = "user@example.com", name = "Test User" },
              subject = "Welcome to AutoSend 🎉",

              // Option 1: Template
              templateId = "your_template_id",

              // Option 2: Raw HTML / text
              html = "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
              text = "Hello User,
  Thanks for joining AutoSend!",

              // Optional unsubscribe group
              unsubscribeGroupId = "12345"
          };

          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_API_KEY");  // Replace with your API key

              var json = JsonConvert.SerializeObject(payload);
              var content = new StringContent(json, Encoding.UTF8, "application/json");

              var response = await client.PostAsync(url, content);
              var responseBody = await response.Content.ReadAsStringAsync();

              Console.WriteLine($"Status: {response.StatusCode}");
              Console.WriteLine($"Response: {responseBody}");
          }
      }
  }
  ```

  ```java Java expandable theme={null}
  import java.io.OutputStream;
  import java.io.InputStream;
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.nio.charset.StandardCharsets;

  public class SendEmail {
      public static void main(String[] args) {
          try {
              String url = "https://api.autosend.com/v1/mails/send";
              URL obj = new URL(url);
              HttpURLConnection con = (HttpURLConnection) obj.openConnection();

              // Set request method and headers
              con.setRequestMethod("POST");
              con.setRequestProperty("Authorization", "Bearer YOUR_API_KEY"); // Replace with your API key
              con.setRequestProperty("Content-Type", "application/json");
              con.setDoOutput(true);

              // JSON payload
              String jsonPayload = """
              {
                  "from": {"email": "no-reply@example.com", "name": "AutoSend"},
                  "to": {"email": "user@example.com", "name": "Test User"},
                  "subject": "Welcome to AutoSend 🎉",

                  "templateId": "your_template_id",

                  "html": "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
                  "text": "Hello User,\nThanks for joining AutoSend!",

                  "unsubscribeGroupId": "12345"
              }
              """;

              // Send request
              try (OutputStream os = con.getOutputStream()) {
                  byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
                  os.write(input, 0, input.length);
              }

              // Read response
              int status = con.getResponseCode();
              InputStream responseStream = (status < HttpURLConnection.HTTP_BAD_REQUEST)
                      ? con.getInputStream()
                      : con.getErrorStream();

              String response = new String(responseStream.readAllBytes(), StandardCharsets.UTF_8);
              System.out.println("Status: " + status);
              System.out.println("Response: " + response);

          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  ```

  ```python Python expandable theme={null}
  import requests

  url = "https://api.autosend.com/v1/mails/send"

  payload = {
      "from": {
          "email": "no-reply@example.com",
          "name": "AutoSend"
      },
      "to": {
          "email": "user@example.com",
          "name": "Test User"
      },
      "subject": "Welcome to AutoSend 🎉",

      # Option 1: Send using template
      "templateId": "your_template_id",

      # Option 2: Send using raw HTML or text
      "html": "<h1>Hello User</h1><p>Thanks for joining AutoSend!</p>",
      "text": "Hello User,
  Thanks for joining AutoSend!",

      # Optional: Unsubscribe group for compliance
      "unsubscribeGroupId": "12345"
  }

  headers = {
      "Authorization": "Bearer YOUR_API_KEY",  # Replace with your API key
      "Content-Type": "application/json"
  }

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

  print("Status Code:", response.status_code)
  print("Response:", response.text)
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
	"success": true,
	"data": {
		"emailId": "698afb75ff4bc5466e3a797a",
		"message": " Email queued successfully.",
		"totalRecipients": 1
	}
}
```
