Skip to content

Code Examples

Ready-to-use code examples for common API operations.

Python

Setup

python
import os
import requests

API_BASE = "https://app.mailshield.app/api/v1"
API_TOKEN = os.environ.get("MAILSHIELD_API_TOKEN")

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

def api_get(endpoint, params=None):
    response = requests.get(f"{API_BASE}{endpoint}", headers=headers, params=params)
    response.raise_for_status()
    return response.json()["data"]

def api_post(endpoint, data=None):
    response = requests.post(f"{API_BASE}{endpoint}", headers=headers, json=data)
    response.raise_for_status()
    return response.json()["data"]

List All Domains

python
domains = api_get("/domains")
for domain in domains:
    print(f"{domain['domain']}: verified={domain['verified']}")

Add a Domain

python
new_domain = api_post("/domains", {
    "domain": "example.com",
    "testEmailLocalPart": "admin",
    "usageType": "sends-and-receives"
})
print(f"Created domain: {new_domain['id']}")
print(f"Verify with TXT record: {new_domain['verificationToken']}")

Check Domain Security

python
domain_id = "550e8400-e29b-41d4-a716-446655440000"

# Trigger checks
results = api_post(f"/domains/{domain_id}/checks")
print(f"Checked at: {results['checkedAt']}")

# Get score
score = api_get(f"/domains/{domain_id}/score")
print(f"Score: {score['score']} ({score['grade']})")

Monitor DMARC Pass Rate

python
from datetime import datetime, timedelta

domain_id = "550e8400-e29b-41d4-a716-446655440000"
start_date = (datetime.now() - timedelta(days=7)).isoformat() + "Z"

reports = api_get(f"/domains/{domain_id}/reports/dmarc", {
    "startDate": start_date
})

if reports["summary"]["totalMessages"] > 0:
    pass_rate = reports["summary"]["passRate"]
    print(f"7-day DMARC pass rate: {pass_rate}%")

Node.js / TypeScript

Setup

typescript
const API_BASE = 'https://app.mailshield.app/api/v1';
const API_TOKEN = process.env.MAILSHIELD_API_TOKEN;

const headers = {
  'Authorization': `Bearer ${API_TOKEN}`,
  'Content-Type': 'application/json',
};

async function apiGet<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
  const url = new URL(`${API_BASE}${endpoint}`);
  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      url.searchParams.set(key, value);
    });
  }

  const response = await fetch(url.toString(), { headers });
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }

  const { data } = await response.json();
  return data;
}

async function apiPost<T>(endpoint: string, body?: unknown): Promise<T> {
  const response = await fetch(`${API_BASE}${endpoint}`, {
    method: 'POST',
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }

  const { data } = await response.json();
  return data;
}

List All Domains

typescript
interface Domain {
  id: string;
  domain: string;
  verified: boolean;
  usageType: string;
}

const domains = await apiGet<Domain[]>('/domains');
domains.forEach(domain => {
  console.log(`${domain.domain}: verified=${domain.verified}`);
});

Add and Verify a Domain

typescript
// Create domain
const newDomain = await apiPost<Domain>('/domains', {
  domain: 'example.com',
  testEmailLocalPart: 'admin',
});

console.log(`Add TXT record: _mailshield.example.com`);
console.log(`Value: mailshield-verify=${newDomain.verificationToken}`);

// Later, verify the domain
const verification = await apiPost<{ verified: boolean }>(`/domains/${newDomain.id}/verify`);
console.log(`Verified: ${verification.verified}`);

Get Security Scores for All Domains

typescript
interface Score {
  score: number | null;
  grade: string | null;
  label: string;
}

const domains = await apiGet<Domain[]>('/domains');

for (const domain of domains) {
  const score = await apiGet<Score>(`/domains/${domain.id}/score`);

  if (score.score !== null) {
    console.log(`${domain.domain}: ${score.score} (${score.grade})`);
  } else {
    console.log(`${domain.domain}: Not checked`);
  }
}

cURL

List Domains

bash
curl -H "Authorization: Bearer $MAILSHIELD_API_TOKEN" \
  https://app.mailshield.app/api/v1/domains

Create Domain

bash
curl -X POST \
  -H "Authorization: Bearer $MAILSHIELD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"domain": "example.com", "testEmailLocalPart": "admin"}' \
  https://app.mailshield.app/api/v1/domains

Run DNS Checks

bash
curl -X POST \
  -H "Authorization: Bearer $MAILSHIELD_API_TOKEN" \
  https://app.mailshield.app/api/v1/domains/550e8400-e29b-41d4-a716-446655440000/checks

Get Score

bash
curl -H "Authorization: Bearer $MAILSHIELD_API_TOKEN" \
  https://app.mailshield.app/api/v1/domains/550e8400-e29b-41d4-a716-446655440000/score

Get DMARC Reports (Last 7 Days)

bash
curl -H "Authorization: Bearer $MAILSHIELD_API_TOKEN" \
  "https://app.mailshield.app/api/v1/domains/550e8400.../reports/dmarc?startDate=$(date -v-7d -u +%Y-%m-%dT00:00:00Z)"

Go

Setup

go
package main

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

const apiBase = "https://app.mailshield.app/api/v1"

var apiToken = os.Getenv("MAILSHIELD_API_TOKEN")

func apiGet(endpoint string) (map[string]interface{}, error) {
	req, _ := http.NewRequest("GET", apiBase+endpoint, nil)
	req.Header.Set("Authorization", "Bearer "+apiToken)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	return result["data"].(map[string]interface{}), nil
}

List Domains

go
func main() {
	data, _ := apiGet("/domains")
	domains := data.([]interface{})

	for _, d := range domains {
		domain := d.(map[string]interface{})
		fmt.Printf("%s: verified=%v\n", domain["domain"], domain["verified"])
	}
}

Monitor and secure your email domains.