Mail Sender docs Retour à l'application →

Exemples de code

Le même envoi, dans les langages les plus courants.

cURL — POST simple

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -d "to=client@example.com" \
  -d "from=contact@mondomaine.com" \
  -d "subject=Bonjour" \
  -d "body=Ceci est un test."

cURL — tous les champs d'adresses

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -d "from=Service client <contact@mondomaine.com>" \
  -d "to=Alice <alice@example.com>, bob@example.com" \
  -d "cc=manager@mondomaine.com" \
  -d "bcc=archive@mondomaine.com" \
  -d "reply_to=support@mondomaine.com" \
  -d "subject=Suivi de votre dossier" \
  --data-urlencode "body=Bonjour,

Votre dossier a bien été mis à jour.

Cordialement,
Le service client"

cURL — HTML

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -d "to=client@example.com" \
  -d "from=contact@mondomaine.com" \
  -d "subject=Bienvenue !" \
  -d "format=html" \
  --data-urlencode 'body=<div style="font-family:sans-serif;max-width:600px">
  <h1 style="color:#0f9b8e">Bienvenue !</h1>
  <p>Votre compte est actif. <a href="https://mondomaine.com/connexion">Se connecter</a></p>
</div>' \
  --data-urlencode "text_body=Bienvenue ! Votre compte est actif : https://mondomaine.com/connexion"

cURL — corps JSON

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["alice@example.com", "bob@example.com"],
    "cc": ["manager@mondomaine.com"],
    "from": "contact@mondomaine.com",
    "subject": "Rapport hebdomadaire",
    "format": "html",
    "body": "<p>Le rapport de la semaine est disponible.</p>"
  }'

cURL — template avec variables

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -d "template=confirmation-commande" \
  -d "to=alice@example.com" \
  -d "from=contact@mondomaine.com" \
  --data-urlencode 'vars={"prenom":"Alice","numero_commande":"CMD-1042","montant":"89,90"}'

cURL — pièce jointe

bash
curl -X POST "https://mailer.echange.online/api/send.php" \
  -H "X-API-Key: $MAIL_SENDER_KEY" \
  -F "to=client@example.com" \
  -F "from=facturation@mondomaine.com" \
  -F "subject=Votre facture" \
  -F "body=La facture est en pièce jointe." \
  -F "attachments[]=@facture-2026-01.pdf"

PHP (cURL, sans dépendance)

php
<?php

function envoyer_email(array $params): array
{
    $ch = curl_init('https://mailer.echange.online/api/send.php');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('MAIL_SENDER_KEY')],
        CURLOPT_POSTFIELDS => http_build_query($params),
    ]);

    $body = curl_exec($ch);
    if ($body === false) {
        throw new RuntimeException('Appel API impossible : ' . curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode((string) $body, true) ?: [];
    if ($status !== 200 || empty($data['success'])) {
        throw new RuntimeException(
            ($data['error']['code'] ?? 'http_' . $status) . ' : '
            . ($data['error']['message'] ?? 'erreur inconnue')
        );
    }

    return $data;
}

$resultat = envoyer_email([
    'to' => 'client@example.com',
    'from' => 'contact@mondomaine.com',
    'subject' => 'Bonjour',
    'format' => 'html',
    'body' => '<p>Ceci est un test.</p>',
]);

echo $resultat['message_id'], PHP_EOL;

Python (requests)

python
import os
import requests

reponse = requests.post(
    "https://mailer.echange.online/api/send.php",
    headers={"X-API-Key": os.environ["MAIL_SENDER_KEY"]},
    json={
        "to": ["alice@example.com", "bob@example.com"],
        "from": "contact@mondomaine.com",
        "subject": "Rapport hebdomadaire",
        "format": "html",
        "body": "<p>Le rapport de la semaine est disponible.</p>",
    },
    timeout=30,
)

donnees = reponse.json()
if not donnees.get("success"):
    raise RuntimeError(donnees["error"]["message"])

print("Envoyé :", donnees["message_id"])

Node.js (fetch natif, Node 18+)

javascript
const reponse = await fetch("https://mailer.echange.online/api/send.php", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.MAIL_SENDER_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to: "client@example.com",
    from: "contact@mondomaine.com",
    subject: "Bonjour",
    format: "html",
    body: "<p>Ceci est un test.</p>",
  }),
});

const donnees = await reponse.json();
if (!donnees.success) {
  throw new Error(`${donnees.error.code} : ${donnees.error.message}`);
}
console.log("Envoyé :", donnees.message_id);

Formulaire de contact (PHP côté serveur)

Le cas d'usage le plus fréquent : un formulaire public, dont le contenu est envoyé par email à votre équipe. Notez le reply_to — il permet de répondre directement au visiteur depuis sa boîte mail.

php
<?php
// traitement-contact.php — appelé par le formulaire de votre site

$nom = trim($_POST['nom'] ?? '');
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
$message = trim($_POST['message'] ?? '');

if ($nom === '' || $email === false || $message === '') {
    http_response_code(422);
    exit('Formulaire incomplet.');
}

$ch = curl_init('https://mailer.echange.online/api/send.php');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('MAIL_SENDER_KEY')],
    CURLOPT_POSTFIELDS => http_build_query([
        'to' => 'contact@mondomaine.com',
        'from' => 'site@mondomaine.com',
        // On répond au visiteur, mais on n'envoie PAS depuis son adresse :
        // usurper le domaine d'un tiers ferait échouer SPF/DMARC.
        'reply_to' => sprintf('%s <%s>', $nom, $email),
        'subject' => 'Message du formulaire de contact',
        'body' => "De : $nom <$email>\n\n$message",
    ]),
]);
curl_exec($ch);
curl_close($ch);

header('Location: /merci.html');

Attention

La clé API doit rester côté serveur. N'appelez jamais cette API directement en JavaScript depuis un navigateur : la clé serait visible par tout visiteur, qui pourrait vider votre quota et envoyer des messages en votre nom.

Gérer les erreurs correctement

php
<?php
// Repli et journalisation : ne perdez jamais un email silencieusement.
try {
    $resultat = envoyer_email($params);
    $logger->info('Email envoyé', ['message_id' => $resultat['message_id']]);
} catch (RuntimeException $e) {
    // 429 : quota ou débit dépassé -> réessayer plus tard (file d'attente)
    // 502 : échec SMTP -> alerter l'exploitation
    // 4xx : requête invalide -> corriger l'appel, inutile de réessayer
    $logger->error('Envoi échoué', ['erreur' => $e->getMessage(), 'params' => $params]);
    $file_attente->pousser($params);
}