Emalc

Search Documentation

Quickly jump to any guide, document, or section...

Code Examples & Integration Snippets

Integration examples for the Emalc Public Email API across multiple languages and tools.


1. cURL#

Send Email#

bash
curl -X POST https://www.emalc.com/api/public/email/send \
  -H "Authorization: Bearer em_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "customer@example.com",
    "from": "Acme Store <orders@yourdomain.com>",
    "subject": "Your receipt from Acme",
    "html": "<h1>Thank you for your purchase!</h1>",
    "text": "Thank you for your purchase!",
    "tracking": { "openTracking": true, "clickTracking": true }
  }'

Fetch Email Delivery Telemetry#

bash
curl -X GET https://www.emalc.com/api/public/email/7132fa69-9064-44d4-9d41-4560ea605dfa \
  -H "Authorization: Bearer em_your_api_key_here"

2. Node.js / TypeScript (Native fetch)#

typescript
interface SendEmailResponse {
  success: boolean;
  id?: string;
  emailId?: string;
  accepted?: string[];
  suppressed?: string[];
  insufficientCredit?: string[];
  error?: string;
  message?: string;
  issues?: unknown[];
}

async function sendTransactionalEmail() {
  const apiKey = process.env.EMALC_API_KEY || 'em_your_api_key_here';

  try {
    const response = await fetch('https://www.emalc.com/api/public/email/send', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: ['customer@example.com'],
        from: 'Acme Store <orders@yourdomain.com>',
        subject: 'Welcome to Acme!',
        html: '<h1>Welcome!</h1><p>We are thrilled to have you onboard.</p>',
        text: 'Welcome! We are thrilled to have you onboard.',
        tracking: { openTracking: true, clickTracking: true },
        tags: { env: 'production', workflow: 'onboarding' },
        idempotencyKey: 'welcome_user_9921',
      }),
    });

    const data: SendEmailResponse = await response.json();

    if (!response.ok) {
      console.error(`Emalc API Error [${response.status}] (${data.error}):`, data.message);
      if (data.issues) console.error('Validation issues:', data.issues);
      return;
    }

    console.log('Dispatched successfully!');
    console.log('AWS Message ID:', data.id);
    console.log('Emalc Email UUID:', data.emailId);
    console.log('Accepted recipients:', data.accepted);

    if (data.suppressed?.length) {
      console.warn('Suppressed recipients:', data.suppressed);
    }
  } catch (err) {
    console.error('Network failure:', err);
  }
}

sendTransactionalEmail();

3. Python (requests)#

python
import os
import requests

url = "https://www.emalc.com/api/public/email/send"
api_key = os.getenv("EMALC_API_KEY", "em_your_api_key_here")

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

payload = {
    "to": ["customer@example.com"],
    "from": "Acme Store <orders@yourdomain.com>",
    "subject": "Password Reset Link",
    "html": "<p>Click <a href='https://yourdomain.com/reset'>here</a> to reset your password.</p>",
    "text": "Click here to reset your password: https://yourdomain.com/reset",
    "tracking": {"openTracking": True, "clickTracking": True},
    "tags": {"category": "auth"},
}

try:
    response = requests.post(url, json=payload, headers=headers, timeout=10)
    data = response.json()

    if response.status_code == 200:
        print(f"Success! Email ID: {data.get('emailId')}, AWS Message ID: {data.get('id')}")
    else:
        print(f"Error {response.status_code} ({data.get('error')}): {data.get('message')}")
except Exception as e:
    print(f"Request failed: {e}")

4. PHP (cURL)#

php
<?php

$apiKey = getenv('EMALC_API_KEY') ?: 'em_your_api_key_here';
$ch = curl_init('https://www.emalc.com/api/public/email/send');

$payload = json_encode([
    'to'       => ['customer@example.com'],
    'from'     => 'Acme Store <orders@yourdomain.com>',
    'subject'  => 'Monthly Account Statement',
    'html'     => '<p>Your monthly statement is ready to view.</p>',
    'text'     => 'Your monthly statement is ready to view.',
    'tracking' => ['openTracking' => true, 'clickTracking' => true],
]);

curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS     => $payload,
]);

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

$result = json_decode($response, true);

if ($httpCode === 200) {
    echo "Dispatched! Email ID: " . $result['emailId'] . "\n";
} else {
    echo "Error ($httpCode - " . ($result['error'] ?? 'UNKNOWN') . "): " . ($result['message'] ?? 'Failed') . "\n";
}

5. Go#

go
package main

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

type TrackingOptions struct {
	OpenTracking  bool `json:"openTracking,omitempty"`
	ClickTracking bool `json:"clickTracking,omitempty"`
}

type SendEmailPayload struct {
	To       []string        `json:"to"`
	From     string          `json:"from"`
	Subject  string          `json:"subject"`
	HTML     string          `json:"html"`
	Text     string          `json:"text,omitempty"`
	Tracking TrackingOptions `json:"tracking"`
}

func main() {
	apiKey := os.Getenv("EMALC_API_KEY")
	if apiKey == "" {
		apiKey = "em_your_api_key_here"
	}

	payload := SendEmailPayload{
		To:      []string{"customer@example.com"},
		From:    "Acme Store <orders@yourdomain.com>",
		Subject: "System Alert",
		HTML:    "<p>Your task processing has finished.</p>",
		Text:    "Your task processing has finished.",
		Tracking: TrackingOptions{
			OpenTracking:  true,
			ClickTracking: true,
		},
	}

	body, _ := json.Marshal(payload)
	req, _ := http.NewRequest("POST", "https://www.emalc.com/api/public/email/send", bytes.NewBuffer(body))
	req.Header.Set("Authorization", "Bearer "+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, _ := io.ReadAll(resp.Body)
	fmt.Printf("HTTP Status: %d\nResponse: %s\n", resp.StatusCode, string(respBody))
}