MailSenpai / SMTP Senpai / API

Developer documentation

SMTP Senpai API and SMTP

Send your software's transactional emails with a REST call that answers in JSON, or over SMTP with a username and password. With the same key you read the sending log and manage the addresses you no longer email. Plus, an address to plug into your website form.

Base URLhttps://app.mailsenpai.com/relay/v1
AuthenticationBearer msp_…
FormatJSON · UTF-8
SMTPrelay.mailsenpai.com:2525 or :587 · STARTTLS

Coming from another email API? SMTP Senpai also accepts requests in the format of 14 other transactional email APIs: change the base URL and the key, keep your code (paths /relay/compat/<service>/ or dedicated hosts such as sendgrid-api.mailsenpai.com). Everything you can connect: integrations.

New in version 1.2: compatible APIs, deliverability headers (List-Unsubscribe One-Click, Feedback-ID…) and up to 500 recipients per call.

Trademarks belong to their respective owners.

Page contents
  1. Overview
  2. Authentication
  3. First send in one minute
  4. Node, Python, PHP examples
  5. Endpoint reference
    1. POST /send
    2. GET /status
    3. GET /statistics
    4. GET /events
    5. GET /suppressions
    6. POST /suppress
    7. POST /unsuppress
  6. Webhook
  7. Errors
  8. Limits
  9. Website forms
  10. SMTP
  11. Best practices
  12. FAQ

Three ways to send

They all lead to the same servers, with the same DKIM signature on your domain, the same log and the same suppression list. Pick the one that fits what you already have.

API REST

One HTTPS call per email, JSON response with the outcome. Ideal for custom software, serverless functions and automations.

SMTP

Server, port, username and password: works with any mail program or library. Supports attachments and multiple recipients.

Website forms

An address for your form's action attribute: every submission reaches you by email. No server-side code.

Before sending you need a verified domain: the customer area shows the DNS records to publish (they sign your emails with DKIM on your domain) and we check them. The sender of every email must be on that domain or one of its subdomains.

Authentication

Every API call carries your key in the header Authorization: Bearer msp_…. The key starts with msp_ and is 52 characters long: you find it in the customer area, SMTP Senpai page, Key for your applications box.

HTTP
Authorization: Bearer msp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  • If you regenerate it in the customer area, the old one stops working immediately.
  • Keep it on the server, in an environment variable: the API does not accept browser calls (it sends no CORS headers), so the key never ends up in a web page. For website forms use theform endpoint, which needs no key.
  • If your platform cannot set custom headers, you can pass the key in the chiave field of the body (JSON or form). GET requests must use the Authorization: Bearer header. A key passed as a URL parameter is rejected with HTTP 401; keep it out of URLs, which may be recorded in server and proxy logs.
  • SMTP credentials (username and password) are separate from the API key and are changed separately.

Missing or wrong key:

HTTP 401
{
  "ok": false,
  "errore": "chiave non valida"
}

Your first send in one minute

  1. Verify the domain you will send from (customer area, Domains page). If you have just started the trial, it is the domain you entered when signing up.
  2. Copy the key and put it in an environment variable: export SMTPSENPAI_KEY=msp_…
  3. Run this request, with a recipient of yours and a sender on the verified domain:
curl
curl https://app.mailsenpai.com/relay/v1/send \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "customer@example.com",
    "from": "orders@yourdomain.com",
    "subject": "Test from SMTP Senpai",
    "text": "It works!"
  }'

If the sending service accepts the request, you get a response like this. Acceptance does not prove delivery to the recipient or placement in the inbox; check the sending log and the receiving mailbox:

HTTP 200
{
  "ok": true,
  "inviato": true,
  "id_messaggio": "9f2c4e1a7b3d5f6e8a9b0c1d@yourdomain.com",
  "residuo": 8759,
  "oltre_il_piano": false
}

Keep id_messaggio: it is also the email's Message-ID and helps you find it in the log.

Ready-made examples: Node, Python, PHP

For each language there is a REST API version and an SMTP version. The examples read key, username and password from environment variables: SMTPSENPAI_KEY, SMTPSENPAI_USER, SMTPSENPAI_PASSWORD.

For a walkthrough of connecting a Next.js form to a server-side sending route, see Manish Tamang’s Next.js and Nodemailer tutorial. His example uses Gmail and an App Password. To send with SMTP Senpai instead, use the relay settings below, keep credentials on the server, and verify your sender domain.

Node.js · fetch
// Node.js 18+: fetch is built in
async function sendEmail() {
  const response = await fetch('https://app.mailsenpai.com/relay/v1/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SMTPSENPAI_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      to: 'customer@example.com',
      from: 'orders@yourdomain.com',
      from_name: 'Your shop',
      subject: 'Order 10293 confirmed',
      html: '<p>Thanks, your order is confirmed.</p>',
      reply_to: 'support@yourdomain.com',
    }),
  });
  const result = await response.json();
  if (!result.ok) {
    throw new Error(`${response.status}: ${result.errore}`);
  }
  console.log(result.inviato ? `Sent: ${result.id_messaggio}` : `Not sent: ${result.motivo}`);
}

sendEmail().catch((e) => { console.error(e.message); process.exitCode = 1; });

REST API, no dependencies.

Node.js · Nodemailer
// npm install nodemailer
const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  host: 'relay.mailsenpai.com',
  port: 2525,
  secure: false,      // start in plain text...
  requireTLS: true,   // ...and upgrade to STARTTLS right away
  auth: {
    user: process.env.SMTPSENPAI_USER,
    pass: process.env.SMTPSENPAI_PASSWORD,
  },
});

async function sendEmail() {
  const info = await transporter.sendMail({
    from: '"Your shop" <orders@yourdomain.com>',
    to: 'customer@example.com',
    subject: 'Your invoice',
    text: 'Please find your invoice attached.',
    html: '<p>Please find your invoice attached.</p>',
    attachments: [{ filename: 'invoice.pdf', path: './invoice.pdf' }],
  });
  console.log('Accepted:', info.messageId);
}

sendEmail().catch((e) => { console.error(e.message); process.exitCode = 1; });

Over SMTP, with an attachment.

Python · requests
# pip install requests
import os
import requests

response = requests.post(
    "https://app.mailsenpai.com/relay/v1/send",
    headers={"Authorization": f"Bearer {os.environ['SMTPSENPAI_KEY']}"},
    json={
        "to": "customer@example.com",
        "from": "orders@yourdomain.com",
        "from_name": "Your shop",
        "subject": "Order 10293 confirmed",
        "html": "<p>Thanks, your order is confirmed.</p>",
        "text": "Thanks, your order is confirmed.",
    },
    timeout=30,
)
result = response.json()
if not result["ok"]:
    raise RuntimeError(f"{response.status_code}: {result['errore']}")
print(result["id_messaggio"] if result["inviato"] else result["motivo"])

REST API.

Python · smtplib
import os
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "Your shop <orders@yourdomain.com>"
msg["To"] = "customer@example.com"
msg["Subject"] = "Your invoice"
msg.set_content("Please find your invoice attached.")
msg.add_alternative("<p>Please find your invoice attached.</p>", subtype="html")
with open("invoice.pdf", "rb") as attachment:
    msg.add_attachment(attachment.read(), maintype="application",
                       subtype="pdf", filename="invoice.pdf")

with smtplib.SMTP("relay.mailsenpai.com", 2525, timeout=30) as server:
    server.starttls()
    server.login(os.environ["SMTPSENPAI_USER"], os.environ["SMTPSENPAI_PASSWORD"])
    server.send_message(msg)

Over SMTP, standard library only, with an attachment.

PHP · cURL
<?php
$ch = curl_init('https://app.mailsenpai.com/relay/v1/send');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . getenv('SMTPSENPAI_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS     => json_encode([
        'to' => 'customer@example.com',
        'from' => 'orders@yourdomain.com',
        'from_name' => 'Your shop',
        'subject' => 'Order 10293 confirmed',
        'html' => '<p>Thanks, your order is confirmed.</p>',
    ], JSON_UNESCAPED_UNICODE),
]);
$body   = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode((string) $body, true);
if (empty($result['ok'])) {
    throw new RuntimeException($status . ': ' . ($result['errore'] ?? 'invalid response'));
}
echo $result['inviato'] ? $result['id_messaggio'] : $result['motivo'];

REST API, no dependencies.

PHP · PHPMailer
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host       = 'relay.mailsenpai.com';
$mail->Port       = 2525;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Username   = getenv('SMTPSENPAI_USER');
$mail->Password   = getenv('SMTPSENPAI_PASSWORD');
$mail->CharSet    = 'UTF-8';

$mail->setFrom('orders@yourdomain.com', 'Your shop');
$mail->addAddress('customer@example.com');
$mail->Subject = 'Your invoice';
$mail->isHTML(true);
$mail->Body    = '<p>Please find your invoice attached.</p>';
$mail->AltBody = 'Please find your invoice attached.';
$mail->addAttachment('invoice.pdf');
$mail->send();

Over SMTP, with an attachment.

In the customer area, Ready-made examples box, you also find the WordPress setup (WP Mail SMTP or FluentSMTP) already filled in with your details.

Tested example: FluentSMTP. On 20 October 2026, an isolated WordPress 7.1.3 installation with FluentSMTP 2.4.1 sent one wp_mail notification through Other SMTP, relay.mailsenpai.com:2525, STARTTLS and certificate verification. The message was received in our own test mailbox with a valid DKIM signature. Use TLS and authentication, the SMTP credentials from your customer area and a verified sender domain. Keep only one mailer plugin active. This test does not certify newsletter scheduling, bounce processing or compatibility with every host. FluentSMTP setup documentation.

Tested transport: MailPoet 5.43.0. On 21 October 2026, an isolated WordPress 7.1.3 installation exercised MailPoet's own SMTP transport on relay.mailsenpai.com:587 with authentication, STARTTLS and certificate validation. One internal demonstration message arrived with DKIM passing. A deliberately unreachable local SMTP endpoint returned a sending error. The received message contained the configured List-Unsubscribe and one-click headers; its demonstration URL was not an unsubscribe service. This verifies the direct transport path, not the newsletter queue, retries, sending-rate control, bounce or suppression lifecycle. Before a production campaign, test those separately against your plan limits and MailPoet's current setup instructions. Do not change a live campaign to reproduce this test.

GoHighLevel: a test notification with Other SMTP

On 20 October 2026 we tested a single internal email from GoHighLevel through Other SMTP, relay.mailsenpai.com, port 587. The receiving mailbox recorded our relay as the sending server and a valid DKIM signature for our verified sender domain. This verifies that sending route in the tested sub-account; it does not establish a native marketplace partnership or test all campaigns, workflows, statistics and bounce processing.

Use the SMTP username and password shown in your SMTP Senpai customer area, a verified sending domain and the STARTTLS configuration. Saving a provider does not activate it: HighLevel uses one active provider at a time. Start in an isolated test sub-account. If an existing account is used, assess any live workflows, obtain approval for a temporary provider switch and restore the previous provider immediately after the test. In our test LeadConnector was restored and the dedicated-domain assignments were preserved. HighLevel SMTP setup; send a test email in Conversations.

Smart Form Builder: the tested SMTP path

Smart Form Builder by Dragwyb has an existing SMTP configuration and Test Email function. Use relay.mailsenpai.com, authenticated STARTTLS on 587, certificate verification, a verified sending domain and the SMTP credentials from your SMTP Senpai service area. Follow the maintainer's SMTP configuration guide and avoid competing site-wide mail transports.

On 28 October 2026 we checked version 1.3.6 with WordPress 7.1.3 and PHP 8.3.36 in isolated staging. Its native Test Email method, called directly with in-memory settings and Apply to all site emails off, reported a controlled connection failure, then sent one message to our own mailbox on 587 with STARTTLS and certificate verification. The received headers showed DKIM pass. Saved settings and the mail-blocking guard were preserved. The maintainer confirmed the shared Dragwyb_Mailer/wp_mail path and reviewed the configuration.

This verifies the bounded basic SMTP path; it does not test a browser settings save, full form submission, background queue, production traffic or bounce/complaint handling. Those behaviours need separate checks before customer use. A named SMTP Senpai provider preset or vendor catalogue listing is not claimed. Versioned method, result and limits.

EventSentry: vendor guide and the 6.0.1.90 test

NETIKUS has published a guide to sending EventSentry alerts through SMTP Senpai, crediting MailSenpai's contribution. It covers a verified sender domain, SMTP credentials, relay.mailsenpai.com:587, TLS (verify), and the difference between a console test and alerts sent by the Collector. Check connectivity from the computer that sends the message: TCP reachability alone does not verify TLS, authentication or delivery.

On 4 November 2026 we tested EventSentry 6.0.1.90 on Windows Server 2025 in isolation, with the Agent and Collector on the same host. Two synthetic notifications reached our owned mailbox with valid DKIM; a third was dropped by the temporary manual suppression of that test recipient. We did not capture the application's SMTP response for the suppressed case: absence of an error does not prove acceptance. Remote Collectors, load, failover and later releases were not tested. Publication of the guide is not native-provider approval or a delivery guarantee.

SDKs and libraries

Prefer a library to direct HTTP calls? The official packages use this API: npm install @mailsenpai/smtp-senpai (Node.js), npm install @mailsenpai/nestjs (NestJS), pip install mailsenpai (Python, with a Django backend), gem install mailsenpai (Ruby and Rails, on RubyGems), composer require mailsenpai/symfony-mailer symfony/http-client (Symfony) and composer require mailsenpai/laravel (Laravel). The packages for Strapi, Payload, Medusa, Directus, n8n and Activepieces (@mailsenpai/activepieces-piece-smtp-senpai, on npm), with the links to the registries and to the source code on GitLab, are on the Integrations page.

Endpoint reference

Base URL https://app.mailsenpai.com/relay/v1. Every response is JSON with an ok field. Responses use Italian field names. Error messages are in the language of your account (in English and Italian together while the key is still unknown, for example with a wrong key). /send also accepts English field names. The earlier Italian paths (/relay/v1/invio, /stato, /statistiche, /eventi, /soppressi, /sopprimi, /riammetti, /webhook/prova) keep working, with the same responses.

POST/relay/v1/send

Sends an email to one or more recipients (up to 500 per call: each one gets their own copy and identifier), attachments included. Up to 50 recipients the call sends right away and returns 200; from 51 to 500 the request is accepted and queued: response 202 with in_coda, the copies leave within a minute. For CC and BCC use SMTP.

Fields

FieldRequiredDescription
toyesRecipient: one address, or a list of up to 500 addresses (more than 50 are queued, response 202).
fromyesSender, on a verified domain (or one of its subdomains).
subjectyesSubject. Non-ASCII characters are encoded automatically.
html / textat least oneHTML and/or plain-text body. If you send only HTML, we derive the text version.
from_namenoSender display name.
reply_tonoAddress for replies (Reply-To). Ignored if not valid.
headersnoJSON object of custom headers. Accepted: names starting with X- (e.g. X-Order-Id) and the deliverability headers List-Unsubscribe, List-Unsubscribe-Post (One-Click only, with an https URI), List-Id and the other List-*, Feedback-ID, Precedence, In-Reply-To, References, priority and language. Headers that touch the sender, the message structure or the sending server are ignored and listed in intestazioni_ignorate; an invalid value returns 400.

The API field names are Italian; each one also has an English alias, used in the examples on this page:

ItalianEnglish
ato
dafrom
nome_mittentefrom_name
oggettosubject
testotext
rispondi_areply_to
intestazioniheaders
allegatiattachments

Attachments

A list of objects with nome (filename), contenuto (content, base64) and, optionally, tipo (content_type). Up to 10 files and 10 MB in total; executable files (.exe, .js, .bat and similar) are refused.

Several recipients

With a list in to the response reports each outcome in risultati: suppressed recipients are held, the others go out.

Idempotency

Add the Idempotency-Key header (up to 100 characters, for example your order id): if you repeat the same request within 24 hours we return the first response, with the Idempotent-Replayed: true header, and nothing is sent again. The same key with different data returns 422.

curl, two recipients and an attachment
curl https://app.mailsenpai.com/relay/v1/send \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Idempotency-Key: order-10293" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["customer@example.com", "billing@example.com"],
    "from": "orders@yourdomain.com",
    "subject": "Your invoice",
    "text": "Please find your invoice attached.",
    "attachments": [{"filename": "invoice.pdf", "content": "JVBERi0xLjQK...", "content_type": "application/pdf"}]
  }'
HTTP 200, several recipients
{
  "ok": true,
  "inviati": 2,
  "non_inviati": 0,
  "risultati": [
    {"a": "customer@example.com", "inviato": true, "id_messaggio": "9f2c4e1a7b3d5f6e8a9b0c1d@yourdomain.com"},
    {"a": "billing@example.com", "inviato": true, "id_messaggio": "1b7e0d2f4a6c8e9b3d5f7a1c@yourdomain.com"}
  ],
  "residuo": 8757,
  "oltre_il_piano": false
}

The body can be JSON (recommended) or a standard application/x-www-form-urlencoded form.

Example

curl
curl https://app.mailsenpai.com/relay/v1/send \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "customer@example.com",
    "from": "orders@yourdomain.com",
    "subject": "Test from SMTP Senpai",
    "text": "It works!"
  }'

Responses

CodeWhen
200 "inviato": trueAccepted: it goes out right away. The residuo field estimates the remaining volume; oltre_il_piano stays for compatibility and is always false: at the limit sending stops.
200 "inviato": falseThe recipient is on the suppression list: nothing is sent and no volume is used.
400Invalid recipient or sender, missing subject, no body.
403Sender on an unverified domain, or account suspended.
429Monthly volume used up, or hourly or daily limit of the free plan.
502The sending server did not accept the message: the text reports its reply.
409A request with the same Idempotency-Key is still in progress.
413Attachments over 10 MB in total.
422Idempotency-Key already used in the last 24 hours with different data.
HTTP 200, suppressed recipient
{
  "ok": true,
  "inviato": false,
  "motivo": "address on the suppression list"
}

GET/relay/v1/status

Account status, SMTP details (without the password), monthly volume and number of suppressed addresses. stato is active or pending (being activated). per_ora is your plan's hourly pace.

curl
curl https://app.mailsenpai.com/relay/v1/status \
  -H "Authorization: Bearer $SMTPSENPAI_KEY"
HTTP 200
{
  "ok": true,
  "stato": "active",
  "smtp": {
    "server": "relay.mailsenpai.com",
    "porta": 2525,
    "porta_alternativa": 587,
    "utente": "r1234@yourdomain.com",
    "sicurezza": "STARTTLS"
  },
  "volume": {
    "mese": "2026-10",
    "incluso": 10000,
    "usato": 1240,
    "residuo": 8760,
    "per_ora": 400
  },
  "tracciamento": false,
  "soppressi": 17
}

GET/relay/v1/statistics

Totals for the last days and day-by-day trend. Parameter giorni: 1 to 90, default 30. The per_giorno detail covers at most the last 30 days and, with no activity, comes as an empty array []. Opens and clicks appear only if you activated tracking.

curl
curl "https://app.mailsenpai.com/relay/v1/statistics?giorni=7" \
  -H "Authorization: Bearer $SMTPSENPAI_KEY"
HTTP 200
{
  "ok": true,
  "giorni": 7,
  "dati": {
    "sent": 812,
    "delivered": 798,
    "bounce": 9,
    "defer": 14,
    "complaint": 0,
    "tracciamento": "non attivo: ...",
    "tasso_consegna": 98.3,
    "tasso_rimbalzo": 1.11,
    "tasso_segnalazioni": 0.0
  },
  "per_giorno": {
    "2026-09-30": { "delivered": 120, "bounce": 2 },
    "2026-10-01": { "sent": 95, "delivered": 93 }
  }
}

GET/relay/v1/events

The latest events, newest first: the detailed log covers 7 days on the free plan and 90 on paid plans. Parameters: quanti (1 to 500, default 50) and tipo. To read only what is new use the cursor dopo (after): with after=0 you get events oldest first, and the prossimo field is the value to pass in the next call; altri is true if there are more. It is the right way to read them at intervals, without gaps or duplicates. Dates are UTC.

TypeMeaning
sentAccepted via API or form.
deliveredDelivered to the recipient server.
deferDeferred by the recipient: we retry automatically.
bouncePermanent rejection: the address goes on the suppression list.
complaintSpam report: the address goes on the suppression list.
droppedNot sent because the recipient was already suppressed.
open / clickOpens and clicks, only with tracking active (otherwise asking for them returns 403).
curl
curl "https://app.mailsenpai.com/relay/v1/events?tipo=bounce&quanti=20" \
  -H "Authorization: Bearer $SMTPSENPAI_KEY"
HTTP 200
{
  "ok": true,
  "eventi": [
    {
      "event_id": "88213",
      "relay_id": "12",
      "type": "bounce",
      "email": "john@example.com",
      "domain": "example.com",
      "from_domain": "yourdomain.com",
      "code": "550",
      "reason": "5.1.1 user unknown",
      "message_id": "",
      "url": "",
      "happened_at": "2026-10-01 08:42:10"
    }
  ]
}
curl, only what is new
curl "https://app.mailsenpai.com/relay/v1/events?after=88213&limit=100" \
  -H "Authorization: Bearer $SMTPSENPAI_KEY"
HTTP 200
{
  "ok": true,
  "eventi": [ { "event_id": 88214, "type": "delivered", "email": "mario@example.com", "...": "..." } ],
  "prossimo": "88214",
  "altri": false
}

GET/relay/v1/suppressions

The addresses (and whole domains, written @domain.com) we no longer email. Parameters: quanti (1 to 1000, default 100) and cerca. reason is bounce, complaint or manuale; totale counts all entries, ignoring the filter.

curl
curl "https://app.mailsenpai.com/relay/v1/suppressions?cerca=example.com" \
  -H "Authorization: Bearer $SMTPSENPAI_KEY"
HTTP 200
{
  "ok": true,
  "totale": 2,
  "elenco": [
    { "supp_id": "501", "relay_id": "12", "email": "john@example.com",
      "reason": "bounce", "note": "5.1.1 user unknown", "created_at": "2026-10-01 08:42:10" },
    { "supp_id": "488", "relay_id": "12", "email": "@competitor.com",
      "reason": "manuale", "note": "", "created_at": "2026-09-20 10:00:00" }
  ]
}

POST/relay/v1/suppress

Adds an address, or a whole domain (@domain.com or domain.com), to the list. Optional field nota (max 255 characters). Returns {"ok": true, "email": "…", "gia_presente": false}; if the entry was already there gia_presente is true. An invalid entry returns 400.

curl
curl https://app.mailsenpai.com/relay/v1/suppress \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "john@example.com", "nota": "asked not to be contacted"}'

POST/relay/v1/unsuppress

Removes from the list an entry you added yourself. Write it exactly as it appears on the list (domains with the at sign). Addresses that entered because of a bounce or a spam report are re-checked by us: ask for it from the customer area, so no one removes by mistake a block that protects deliverability. For these entries the response is 409; for an entry that is not on the list, 404.

curl
curl https://app.mailsenpai.com/relay/v1/unsuppress \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "john@example.com"}'

Webhooks: outcomes in real time

Instead of reading /events at intervals, you can be notified: for every event on your account we send a JSON POST to the https address you choose. One event per call, so it also works with Zapier, Make and n8n. Set it in the customer area, Real-time notifications box, or with the API below.

EventWhen it arrives
sentAccepted by our servers (via API or form).
deliveredDelivered to the recipient server.
bouncePermanent rejection: the address is suppressed.
deferDeferred: we retry automatically.
complaintMarked as spam.
droppedHeld because the recipient is suppressed.
open / clickOpens and clicks, only with tracking active.

The request body

JSON
{
  "id": "evt_88214",
  "type": "delivered",
  "created_at": "2026-10-09T10:26:01Z",
  "data": {
    "email": "mario@example.com",
    "domain": "example.com",
    "from_domain": "yourdomain.com",
    "code": "2.0.0",
    "reason": "",
    "message_id": "9f2c4e1a7b3d5f6e8a9b0c1d@yourdomain.com",
    "url": ""
  },
  "account": "your-account-code"
}
HeaderContent
X-MailSenpai-EventThe event type.
X-MailSenpai-DeliveryDelivery identifier: it stays the same across retries, use it to avoid recording the same event twice.
X-MailSenpai-Signaturet=<unix>,v1=<hex>: HMAC-SHA256 signature of "<t>.<body>" with your secret (whsec_…).

Answer with a 2xx status within 8 seconds. If your server does not answer or returns an error we retry after 1 minute, 5 minutes, 30 minutes, 2, 6 and 12 hours: about 24 hours in total. Only public https addresses are accepted.

Verifying the signature

Node.js
import crypto from 'node:crypto';

// raw request body (string) and X-MailSenpai-Signature header
function isValidSignature(body, header, secret) {
  const m = /t=(\d+),v1=([a-f0-9]+)/.exec(header || '');
  if (!m) return false;
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false; // max 5 minutes
  const expected = crypto.createHmac('sha256', secret).update(`${m[1]}.${body}`).digest('hex');
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(m[2]));
}
PHP
<?php
$body = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_MAILSENPAI_SIGNATURE'] ?? '';
$secret = getenv('MAILSENPAI_WEBHOOK_SECRET');
if (!preg_match('/t=(\d+),v1=([a-f0-9]+)/', $sig, $m) || abs(time() - (int) $m[1]) > 300
    || !hash_equals(hash_hmac('sha256', $m[1] . '.' . $body, $secret), $m[2])) {
    http_response_code(401); exit;
}
$evento = json_decode($body, true);
http_response_code(200);
Python
import hmac, hashlib, re, time

def is_valid_signature(body: bytes, header: str, secret: str) -> bool:
    m = re.match(r"t=(\d+),v1=([a-f0-9]+)", header or "")
    if not m or abs(time.time() - int(m.group(1))) > 300:
        return False
    expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m.group(2))

Setting it up with the API

CallWhat it does
GET /relay/v1/webhookAddress, chosen events, status and deliveries in the last 24 hours.
POST /relay/v1/webhookSets url, eventi (events), attivo (active); with nuovo_segreto (rotate_secret) generates a new secret. An empty url turns the webhook off. The response contains the secret.
POST /relay/v1/webhook/testSends a test event right away (with "test": true) and tells you what your server answered.
curl
curl https://app.mailsenpai.com/relay/v1/webhook \
  -H "Authorization: Bearer $SMTPSENPAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://yoursite.com/webhook/mailsenpai", "events": ["delivered", "bounce", "complaint"]}'

Errors

An error always has "ok": false and an errore field with the explanation in the language of your account (Italian and English together while the key is still unknown), together with the HTTP status:

CodeMeaningWhat to do
400Missing or invalid data.Fix the request: do not repeat it unchanged.
401Missing or invalid key.Check the Authorization header; if you regenerated the key, update the variable.
403Sender domain not verified, tracking not active, or account suspended (the message says why: plan expired or unpaid, volume used up).Verify the domain or check your plan in the customer area.
404Unknown address (endpoint or form).Check the path.
405Wrong HTTP method (for example POST on /status).Use the method given in the Allow header.
409Entry blocked by our servers (unsuppress) or Idempotency-Key still in progress.Ask for a review in the customer area; for idempotency retry in a few seconds.
413Attachments too large.Stay under 10 MB, or use SMTP (up to 50 MB).
422Idempotency-Key reused with different data, or invalid webhook.Use a new key for each different send.
429Monthly volume used up, or hourly or daily limit of the free plan.For the free plan limits try again later: the message says when. For the monthly volume sending restarts next month, or after payment (usually within an hour) if you increase your volume: when you can do it yourself, the response contains the link to the right page.
502The sending server refused or could not be reached.Retry after a few seconds, with increasing waits. Before retrying, check /events that the email did not already go out.
HTTP 429
{
  "ok": false,
  "errore": "monthly volume used up: sending restarts next month, or after payment if you increase your volume from Boost your plan in your area",
  "residuo": 0,
  "aumenta": "https://app.mailsenpai.com/customer/il-mio-piano",
  "pannello": "https://app.mailsenpai.com/customer/relay-smtp"
}

Limits

WhatLimit
Recipients per API callUp to 500: each one gets their own copy. Up to 50 go out right away, from 51 to 500 they are queued (response 202). Over SMTP you can also address several in one message.
VolumeYour plan's, per calendar month. Emails that reached an outcome count (delivered or bounced); those held by suppression do not. We email you before it runs out.
Volume used upOn the free plan, sending stops at the limits without charging or storing the rejected emails. On paid plans, too, sending stops at the limit until next month, or until you increase the volume and the payment is registered (sending restarts within about an hour).
Hourly paceOn the free plan: up to 30 emails in the preceding hour; further submissions are rejected until capacity is available, without storing the rejected emails. On paid plans, your plan’s pace applies (field per_ora of /status): above that pace messages wait in the queue; with a new dedicated IP the pace ramps up during the first weeks.
API requestsNo declared rate limit: the plan volume still applies.
SMTP message size50 MB
Detailed log7 days on the free plan, 90 on paid plans (/events, up to 500 rows per call); totals are kept longer.
StatisticsUp to 90 days; daily trend up to 30.
IdempotencyWith the Idempotency-Key header the same request repeated within 24 hours is not sent again.
Attachments via API10 files and 10 MB in total, no executables.
Website forms25 forms per account, 3 recipients per form (+1 with _cc), 60 fields of 5,000 characters, 25 submissions per hour from the same network.

Website forms

For websites that cannot send email (static pages, themes without plugins, hosting that blocks mail). Create the form in the customer area, copy its address and put it in the action attribute of your form, with method="POST". No key needed.

HTML
<form action="https://app.mailsenpai.com/relay/f/CODICE" method="POST">
  <label>Name <input type="text" name="name" required></label>
  <label>Email <input type="email" name="email" required></label>
  <label>Message <textarea name="message" required></textarea></label>

  <input type="hidden" name="_subject" value="New enquiry from the website">
  <input type="hidden" name="_next" value="https://www.yoursite.com/thank-you/">
  <input type="text" name="_gotcha" style="display:none" tabindex="-1" autocomplete="off">

  <button type="submit">Send</button>
</form>

Replace CODICE with your form's code. Every submission reaches you by email, laid out, with the Reply-To of the person who wrote: hit reply and you write back.

Special fields

FieldWhat it does
_subjectSubject of the email you receive. Otherwise the one set in the form is used.
_replytoReply address. If missing, we use the first field with mail in its name that contains a valid address.
_nextThank-you page (full address, http or https) for classic submissions, on one of your verified domains or on the same site as the thank-you page set in the form. Otherwise the form's one, or we show a confirmation page.
_ccA copy to another address. Works only if allowed in the form settings.
_gotchaHoneypot: keep it hidden and empty. If a bot fills it, the submission is silently discarded.
_formatWith the value plain you receive the email as plain text.

Other names starting with _ are ignored. Files attached to the form are not forwarded.

Submitting with JavaScript

If you submit the form with fetch and the header Accept: application/json (or a JSON body), the response is JSON and you can stay on the page. The address accepts requests from any website (CORS): to restrict it to yours, list your domains in the form settings.

JavaScript
const form = document.querySelector('form[action*="/relay/f/"]');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const response = await fetch(form.action, {
    method: 'POST',
    body: new FormData(form),
    headers: { Accept: 'application/json' },
  });
  const result = await response.json();
  if (result.ok) {
    form.replaceWith('Thanks, we will get back to you soon.');
  } else {
    alert(result.errore);
  }
});
ResponseWhen
200 {"ok": true, ...}Received and forwarded. With a classic submission: 303 redirect to _next or a confirmation page.
403Form paused, service not active, or website not among the allowed domains.
404Unknown form code.
409No verified sending domain yet.
422The form arrived with no fields filled in.
429Too many submissions from the same network in the last hour, or monthly volume used up.

Form emails are sent from moduli@yourdomain.com, with the form name as sender, and count towards the monthly volume like all the others. Optionally, whoever fills in the form gets an automatic reply in your words, and every submission is archived in the customer area.

SMTP

For programs that already have an SMTP server screen (ERPs, e-commerce, CRMs, WordPress) and when you need attachments or multiple recipients.

SettingValue
Hostrelay.mailsenpai.com
Port2525 or 587 (the ones shown in your area, porta and porta_alternativa fields of /status)
EncryptionSTARTTLS (mandatory: login is only possible after STARTTLS). Plugins often call it TLS.
AuthenticationLOGIN / PLAIN with the username and password from your area
Maximum size50 MB per message, attachments included
Other8BITMIME, SMTPUTF8

What happens over SMTP

  • Sender (From) on an unverified domain: the message is rejected with 550 5.7.1.
  • Recipient on the suppression list: the server answers OK, so your program does not error, but the email is not sent, uses no volume and shows in the log as dropped.
  • Wrong credentials: 535 5.7.8.
  • SMTP sends end up in the same log and statistics as the API.

Best practices

  • Publish all the DNS records shown in your area: the DKIM signature on your domain and SPF tell providers the emails are really yours. Add a DMARC record, starting with p=none.
  • Always send from an address on the verified domain and use reply_to if replies must go elsewhere.
  • Always include a text version, or let us derive it from the HTML: image-only or HTML-only emails perform worse.
  • Let suppression do its job: hard bounces and spam reports are removed from sending automatically. Add yourself anyone who asks not to be contacted.
  • Retry only on temporary errors (502), with increasing waits; never on 400, 401 and 403.
  • Use X-… headers to link the email to your system (order number, user id) and store id_messaggio.
  • Check /statistics now and then: a rising bounce rate is the first sign of a list that needs cleaning.
  • Keep service emails separate from promotional ones: for campaigns there is the MailSenpai platform.

Frequently asked questions

Can I send attachments with the API?

Yes: with the attachments field (base64), up to 10 files and 10 MB in total. For larger messages use SMTP, up to 50 MB (see the Nodemailer, smtplib and PHPMailer examples).

How do I send the same email to several people?

Put up to 500 addresses in a list: each one gets their own copy and outcome, as is right for transactional emails. Above 50 the request is queued (response 202). CC and BCC are available only over SMTP.

Are there webhooks for deliveries and bounces?

Yes: you set an https address and we send a signed POST for every delivery, bounce, deferral, complaint or hold (see the Webhooks section). Alternatively read /events with the after cursor.

Is there a sandbox?

There is no separate sandbox: the free plan gives you a real account to send to your own addresses, with no card and no expiry. The test button in the area sends a verification email with your credentials.

Can I call the API from the browser?

No, by design: the key would let anyone send on your behalf. Call the API from your server or a serverless function. For forms use the form endpoint, which is built for that.

Do emails go out immediately?

Yes: the 200 response arrives once the sending servers have taken the message, and they deliver it right away within your plan's hourly pace. If the recipient server defers, we retry automatically.

What happens when the monthly volume runs out?

We email you before it happens. At the limit sending stops: the API returns 429 and, after the hourly check, 403 with the reason monthly volume used up. Sending restarts when the new month starts, or when you increase the volume and the payment is registered (usually within an hour). Nothing is ever charged beyond what you paid for.

Are emails DKIM-signed?

Yes, on your domain, both via API and SMTP, once you publish the DNS records shown in the customer area.

Can I use SMTP Senpai with Zapier, Make or n8n?

Yes, with the platform's generic HTTP module: POST method, /relay/v1/send address, Authorization header with your key and a JSON body as in the examples. Where there is an SMTP module, you can use that too.

Try it with your domain

Start free with no card and no expiry. API key, SMTP credentials and forms are activated after you confirm your email and verify your domain.