Documentazione API

Integra LegallyMail nella tua applicazione con la nostra API REST

Introduzione

L'API di LegallyMail ti permette di inviare email certificate dalla tua applicazione. Tutti gli invii vengono registrati e puoi ottenere certificati legali di consegna e lettura.

Nota: Solo gli utenti che hanno effettuato almeno un pagamento possono usare l'API e creare token.

Autenticazione

Tutte le richieste all'API richiedono autenticazione tramite un token di accesso. Puoi ottenere il tuo token dal pannello utente.

Metodo 1: Header Authorization

Includi il token nell'header Authorization:

Authorization: Bearer YOUR_TOKEN_HERE

Metodo 2: Nel corpo della richiesta

Includi il token nel JSON del corpo:

{
  "token": "YOUR_TOKEN_HERE",
  "recipient": "example@example.com",
  ...
}

Ottenere un Token

Per ottenere un token API, devi prima aver effettuato almeno un pagamento. Successivamente puoi creare token dal tuo pannello utente.

Accedi

Endpoint

POST /api/send

Invia un'email certificata.

Parametri
Parametro Tipo Richiesto Descrizione
Authorization string (header) Token di autenticazione in formato "Bearer {token}" o solo il token
recipient / to string Indirizzo email del destinatario
subject string Oggetto dell'email
message / body / content string (HTML) Contenuto dell'email in formato HTML
reply_to string (email) No Indirizzo email per le risposte (opzionale)
reply_to_name string No Nome per le risposte (opzionale)
attachments array No Array di file allegati (opzionale). Ogni file deve avere: filename, content (base64), mime_type
Ejemplos de código
curl -X POST https://legallymail.com/api/send \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "recipient": "example@example.com",
    "subject": "Test Email with Attachment",
    "message": "<h1>Hello World</h1><p>This email contains an attachment.</p>",
    "attachments": [
      {
        "filename": "document.pdf",
        "content": "base64_encoded_file_content_here",
        "mime_type": "application/pdf"
      }
    ]
  }'
<?php
$token = 'YOUR_TOKEN_HERE';
$url = 'https://legallymail.com/api/send';

// Leer el archivo y codificarlo en base64
$filePath = '/path/to/document.pdf';
$fileContent = base64_encode(file_get_contents($filePath));

$data = [
    'recipient' => 'example@example.com',
    'subject' => 'Test Email with Attachment',
    'message' => '<h1>Hello World</h1><p>This email contains an attachment.</p>',
    'attachments' => [
        [
            'filename' => 'document.pdf',
            'content' => $fileContent,
            'mime_type' => 'application/pdf'
        ]
    ]
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json'
]);

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

$result = json_decode($response, true);
?>
import requests
import base64

token = 'YOUR_TOKEN_HERE'
url = 'https://legallymail.com/api/send'

# Leer el archivo y codificarlo en base64
with open('/path/to/document.pdf', 'rb') as file:
    file_content = base64.b64encode(file.read()).decode('utf-8')

data = {
    'recipient': 'example@example.com',
    'subject': 'Test Email with Attachment',
    'message': '<h1>Hello World</h1><p>This email contains an attachment.</p>',
    'attachments': [
        {
            'filename': 'document.pdf',
            'content': file_content,
            'mime_type': 'application/pdf'
        }
    ]
}

headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'application/json'
}

response = requests.post(url, json=data, headers=headers)
result = response.json()
const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/send';

// Leer el archivo y codificarlo en base64 (Node.js)
const fs = require('fs');
const filePath = '/path/to/document.pdf';
const fileContent = fs.readFileSync(filePath).toString('base64');

const data = {
    recipient: 'example@example.com',
    subject: 'Test Email with Attachment',
    message: '<h1>Hello World</h1><p>This email contains an attachment.</p>',
    attachments: [
        {
            filename: 'document.pdf',
            content: fileContent,
            mime_type: 'application/pdf'
        }
    ]
};

fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
package main

import (
    'bytes'
    'encoding/base64'
    'encoding/json'
    'io/ioutil'
    'net/http'
)

func main() {
    token := 'YOUR_TOKEN_HERE'
    url := 'https://legallymail.com/api/send'

    // Leer el archivo y codificarlo en base64
    filePath := '/path/to/document.pdf'
    fileContent, _ := ioutil.ReadFile(filePath)
    fileBase64 := base64.StdEncoding.EncodeToString(fileContent)

    data := map[string]interface{}{
        'recipient': 'example@example.com',
        'subject':   'Test Email with Attachment',
        'message':   '<h1>Hello World</h1><p>This email contains an attachment.</p>',
        'attachments': []map[string]string{
            {
                'filename':  'document.pdf',
                'content':   fileBase64,
                'mime_type': 'application/pdf',
            },
        },
    }

    jsonData, _ := json.Marshal(data)

    req, _ := http.NewRequest('POST', url, bytes.NewBuffer(jsonData))
    req.Header.Set('Authorization', 'Bearer '+token)
    req.Header.Set('Content-Type', 'application/json')

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.google.gson.Gson;

public class SendEmail {
    public static void main(String[] args) throws IOException, InterruptedException {
        String token = 'YOUR_TOKEN_HERE';
        String url = 'https://legallymail.com/api/send';

        // Leer el archivo y codificarlo en base64
        String filePath = '/path/to/document.pdf';
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
        String fileBase64 = Base64.getEncoder().encodeToString(fileBytes);

        Map<String, Object> attachment = new HashMap<>();
        attachment.put('filename', 'document.pdf');
        attachment.put('content', fileBase64);
        attachment.put('mime_type', 'application/pdf');

        Map<String, Object> data = new HashMap<>();
        data.put('recipient', 'example@example.com');
        data.put('subject', 'Test Email with Attachment');
        data.put('message', '<h1>Hello World</h1><p>This email contains an attachment.</p>');
        data.put('attachments', Arrays.asList(attachment));

        Gson gson = new Gson();
        String jsonData = gson.toJson(data);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header('Authorization', 'Bearer ' + token)
            .header('Content-Type', 'application/json')
            .POST(HttpRequest.BodyPublishers.ofString(jsonData))
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    }
}
const https = require('https');
const fs = require('fs');

const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/send';

// Leer el archivo y codificarlo en base64
const filePath = '/path/to/document.pdf';
const fileContent = fs.readFileSync(filePath).toString('base64');

const data = {
    recipient: 'example@example.com',
    subject: 'Test Email with Attachment',
    message: '<h1>Hello World</h1><p>This email contains an attachment.</p>',
    attachments: [
        {
            filename: 'document.pdf',
            content: fileContent,
            mime_type: 'application/pdf'
        }
    ]
};

const options = {
    hostname: 'legallymail.com',
    path: '/api/send',
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    }
};

const req = https.request(options, (res) => {
    let responseData = '';
    res.on('data', (chunk) => {
        responseData += chunk;
    });
    res.on('end', () => {
        const result = JSON.parse(responseData);
        console.log(result);
    });
});

req.on('error', (error) => {
    console.error('Error:', error);
});

req.write(JSON.stringify(data));
req.end();
using System;
using System.Net.Http;
using System.Text;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static async System.Threading.Tasks.Task Main()
    {
        string token = 'YOUR_TOKEN_HERE';
        string url = 'https://legallymail.com/api/send';

        // Leer el archivo y codificarlo en base64
        string filePath = '/path/to/document.pdf';
        byte[] fileBytes = File.ReadAllBytes(filePath);
        string fileBase64 = Convert.ToBase64String(fileBytes);

        var attachment = new
        {
            filename = 'document.pdf',
            content = fileBase64,
            mime_type = 'application/pdf'
        };

        var data = new
        {
            recipient = 'example@example.com',
            subject = 'Test Email with Attachment',
            message = '<h1>Hello World</h1><p>This email contains an attachment.</p>',
            attachments = new[] { attachment }
        };

        string jsonData = JsonConvert.SerializeObject(data);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + token);
            var content = new StringContent(jsonData, Encoding.UTF8, 'application/json');

            var response = await client.PostAsync(url, content);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}
Risposta riuscita
{
  "success": true,
  "message": "Email inviata correttamente",
  "data": {
    "tracking_id": "cm_xxx",
    "recipient": "example@example.com",
    "subject": "Test Email",
    "sent_at": "2024-01-01 12:00:00",
    "mailsender_id": "xxx"
  }
}
GET /api/info

Ottiene informazioni sull'API e l'utente autenticato

Restituisce informazioni sull'API e l'utente autenticato, inclusi email, piano sottoscritto ed email rimanenti.

Parametri
Parametro Tipo Richiesto Descrizione
Authorization string (header) Token di autenticazione in formato "Bearer {token}" o solo il token
Ejemplos de código
curl -X GET https://legallymail.com/api/info \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
<?php
$token = 'YOUR_TOKEN_HERE';
$url = 'https://legallymail.com/api/info';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token
]);

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

$result = json_decode($response, true);
?>
import requests

token = 'YOUR_TOKEN_HERE'
url = 'https://legallymail.com/api/info'

headers = {
    'Authorization': f'Bearer {token}'
}

response = requests.get(url, headers=headers)
result = response.json()
const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/info';

fetch(url, {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
package main

import (
    'net/http'
    'io/ioutil'
)

func main() {
    token := 'YOUR_TOKEN_HERE'
    url := 'https://legallymail.com/api/info'

    req, _ := http.NewRequest('GET', url, nil)
    req.Header.Set('Authorization', 'Bearer '+token)

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class GetInfo {
    public static void main(String[] args) throws Exception {
        String token = 'YOUR_TOKEN_HERE';
        String url = 'https://legallymail.com/api/info';

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header('Authorization', 'Bearer ' + token)
            .GET()
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        String result = response.body();
    }
}
const https = require('https');

const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/info';

const options = {
    hostname: 'legallymail.com',
    path: '/api/info',
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
};

const req = https.request(options, (res) => {
    let responseData = '';
    res.on('data', (chunk) => {
        responseData += chunk;
    });
    res.on('end', () => {
        const result = JSON.parse(responseData);
        console.log(result);
    });
});

req.on('error', (error) => {
    console.error('Error:', error);
});

req.end();
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string token = 'YOUR_TOKEN_HERE';
        string url = 'https://legallymail.com/api/info';

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + token);
            
            var response = await client.GetAsync(url);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}
Risposta riuscita
{
  "name": "LegallyMail API",
  "version": "1.0.0",
  "user": {
    "email": "usuario@example.com",
    "name": "Nombre Usuario",
    "plan": "professional",
    "plan_name": "Profesional",
    "plan_limit": 100,
    "extra_emails": 0,
    "remaining_emails": 75
  }
}
GET /api/emails

Ottiene le ultime email inviate

Restituisce un elenco delle ultime email inviate dall'utente autenticato, incluso il loro stato (sent, read, failed). Massimo 25 risultati.

Parametri
Parametro Tipo Richiesto Descrizione
Authorization string (header) Token di autenticazione in formato "Bearer {token}" o solo il token
limit integer (query) Numero di email da restituire (tra 1 e 25). Obbligatorio.
Ejemplos de código
curl -X GET "https://legallymail.com/api/emails?limit=10" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
<?php
$token = 'YOUR_TOKEN_HERE';
$url = 'https://legallymail.com/api/emails?limit=10';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token
]);

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

$result = json_decode($response, true);
?>
import requests

token = 'YOUR_TOKEN_HERE'
url = 'https://legallymail.com/api/emails'
params = {'limit': 10}

headers = {
    'Authorization': f'Bearer {token}'
}

response = requests.get(url, params=params, headers=headers)
result = response.json()
const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/emails?limit=10';

fetch(url, {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
package main

import (
    'net/http'
    'io/ioutil'
)

func main() {
    token := 'YOUR_TOKEN_HERE'
    url := 'https://legallymail.com/api/emails?limit=10'

    req, _ := http.NewRequest('GET', url, nil)
    req.Header.Set('Authorization', 'Bearer '+token)

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class GetEmails {
    public static void main(String[] args) throws Exception {
        String token = 'YOUR_TOKEN_HERE';
        String url = 'https://legallymail.com/api/emails?limit=10';

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header('Authorization', 'Bearer ' + token)
            .GET()
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        String result = response.body();
    }
}
const https = require('https');

const token = 'YOUR_TOKEN_HERE';
const url = 'https://legallymail.com/api/emails?limit=10';

const options = {
    hostname: 'legallymail.com',
    path: '/api/emails?limit=10',
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
};

const req = https.request(options, (res) => {
    let responseData = '';
    res.on('data', (chunk) => {
        responseData += chunk;
    });
    res.on('end', () => {
        const result = JSON.parse(responseData);
        console.log(result);
    });
});

req.on('error', (error) => {
    console.error('Error:', error);
});

req.end();
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string token = 'YOUR_TOKEN_HERE';
        string url = 'https://legallymail.com/api/emails?limit=10';

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + token);
            
            var response = await client.GetAsync(url);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}
Risposta riuscita
{
  "success": true,
  "count": 2,
  "limit": 10,
  "max_limit": 25,
  "emails": [
    {
      "id": 123,
      "tracking_id": "cm_abc123",
      "recipient": "example@example.com",
      "subject": "Test Email",
      "status": "read",
      "sent_at": "2024-01-15 10:30:00",
      "read_at": "2024-01-15 11:00:00",
      "created_at": "2024-01-15 10:30:00",
      "mailsender_id": "mail_xyz789"
    },
    {
      "id": 122,
      "tracking_id": "cm_def456",
      "recipient": "test@example.com",
      "subject": "Another Email",
      "status": "sent",
      "sent_at": "2024-01-14 15:20:00",
      "read_at": null,
      "created_at": "2024-01-14 15:20:00",
      "mailsender_id": "mail_uvw012"
    }
  ]
}
GET /api/email

Ottiene lo stato di un'email specifica

Restituisce le informazioni dettagliate di un'email specifica identificata dal suo tracking_id, incluso il suo stato attuale (sent, read, failed) e le date di invio e lettura.

Parametri
Parametro Tipo Richiesto Descrizione
Authorization string (header) Token di autenticazione in formato "Bearer {token}" o solo il token
tracking_id string (query) L'identificatore unico di tracciamento dell'email (tracking_id) restituito all'invio dell'email.
Ejemplos de código
curl -X GET "https://legallymail.com/api/email?tracking_id=cm_abc123" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
<?php
$token = 'YOUR_TOKEN_HERE';
$trackingId = 'cm_abc123';
$url = 'https://legallymail.com/api/email?tracking_id=' . urlencode($trackingId);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token
]);

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

$result = json_decode($response, true);
?>
import requests

token = 'YOUR_TOKEN_HERE'
url = 'https://legallymail.com/api/email'
params = {'tracking_id': 'cm_abc123'}

headers = {
    'Authorization': f'Bearer {token}'
}

response = requests.get(url, params=params, headers=headers)
result = response.json()
const token = 'YOUR_TOKEN_HERE';
const trackingId = 'cm_abc123';
const url = `https://legallymail.com/api/email?tracking_id=${trackingId}`;

fetch(url, {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
package main

import (
    'net/http'
    'io/ioutil'
    'net/url'
)

func main() {
    token := 'YOUR_TOKEN_HERE'
    trackingId := 'cm_abc123'
    baseUrl := 'https://legallymail.com/api/email'
    
    params := url.Values{}
    params.Add('tracking_id', trackingId)
    fullUrl := baseUrl + '?' + params.Encode()

    req, _ := http.NewRequest('GET', fullUrl, nil)
    req.Header.Set('Authorization', 'Bearer '+token)

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class GetEmail {
    public static void main(String[] args) throws Exception {
        String token = 'YOUR_TOKEN_HERE';
        String trackingId = 'cm_abc123';
        String url = 'https://legallymail.com/api/email?tracking_id=' + trackingId;

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header('Authorization', 'Bearer ' + token)
            .GET()
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        String result = response.body();
    }
}
const https = require('https');

const token = 'YOUR_TOKEN_HERE';
const trackingId = 'cm_abc123';
const url = `https://legallymail.com/api/email?tracking_id=${trackingId}`;

const options = {
    hostname: 'legallymail.com',
    path: `/api/email?tracking_id=${trackingId}`,
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    }
};

const req = https.request(options, (res) => {
    let responseData = '';
    res.on('data', (chunk) => {
        responseData += chunk;
    });
    res.on('end', () => {
        const result = JSON.parse(responseData);
        console.log(result);
    });
});

req.on('error', (error) => {
    console.error('Error:', error);
});

req.end();
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string token = 'YOUR_TOKEN_HERE';
        string trackingId = 'cm_abc123';
        string url = $"https://legallymail.com/api/email?tracking_id={trackingId}";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + token);
            
            var response = await client.GetAsync(url);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}
Risposta riuscita
{
  "success": true,
  "email": {
    "id": 123,
    "tracking_id": "cm_abc123",
    "recipient": "example@example.com",
    "subject": "Test Email",
    "status": "read",
    "sent_at": "2024-01-15 10:30:00",
    "read_at": "2024-01-15 11:00:00",
    "created_at": "2024-01-15 10:30:00",
    "mailsender_id": "mail_xyz789"
  }
}

Codici di Errore

Codice Messaggio Descrizione
400 Bad Request I dati forniti non sono validi
401 Unauthorized Token non valido o non fornito
403 Forbidden Non hai il permesso per eseguire questa azione
Viene restituito anche quando l'utente non ha crediti/email rimanenti disponibili.
404 Not Found Risorsa non trovata. Verifica che la risorsa richiesta esista (ad esempio, un'email con il tracking_id specificato).
405 Method Not Allowed Metodo HTTP non consentito
429 Too Many Requests Troppe richieste. Limite di rate limiting superato.
500 Internal Server Error Errore interno del server

Limiti e Restrizioni

L'API ha le seguenti restrizioni:

  • Solo gli utenti con almeno un pagamento possono usare l'API
  • I limiti di email dipendono dal piano dell'utente
  • Si applicano limiti di velocità per proteggere il servizio
  • Limite di 10 richieste al minuto per indirizzo IP (errore 429 se superato)
Tempo Reale