Email API Integration
Everything you need to send email from your application is on this page: the key, domain verification, the first send, delivery status and webhooks. Pick your language and every example on the page switches to it. If you have an application on Amazon SES, you can move without changing your code, by changing only the endpoint and the key.
Email API integration in five steps
Your language choice is remembered in your browser; when you change it in one example, the others switch too.
-
Create an access key
Create a key in the “Access keys” section of your client area. The secret key is shown only at the moment it is created; store it somewhere safe. You can open a separate key per application and lock a key to specific IP addresses and to a single sender domain.
The three values in the examples are read from environment variables:MXGATE_APIis your account’s API address (shown in your client area),MXGATE_KEYthe access key andMXGATE_SECRETthe secret key. Do not put the key in source code. Calls must come from your server; calling from JavaScript in the browser is not supported, because the secret key would be exposed. -
Verify your sender domain
Add your sender domain in the client area and enter the DKIM and SPF TXT records shown to you into your DNS. Sending opens once both are verified; sends from an unverified domain are refused. Verification runs automatically every few minutes and you can also check right away with the “Check DNS” button.
A domain that is not verified within 7 days is removed automatically; you can add it again. If your domain is also used by a smarthost service, pick a subdomain such asnotify.yourcompany.comfor the API. -
Send your first email
A single HTTPS request is enough. The sender address must be on one of your verified domains. The answer returns a message ID (
message_id) that you use to follow delivery.SEND A MESSAGE · RESTcurl -X POST "$MXGATE_API/v1/email/send" \ -H "Authorization: Bearer $MXGATE_KEY:$MXGATE_SECRET" \ -H "Content-Type: application/json" \ -d '{ "from": "Muhasebe <fatura@bildirim.firma.com>", "to": ["musteri@example.com"], "subject": "Faturanız hazır", "text": "Faturanız ektedir.", "html": "<p>Faturanız ektedir.</p>", "tags": {"tur": "fatura"} }' # -> 202 {"message_id": "...", "status": "accepted"}<?php // PHP 7.4+ · ek paket gerekmez (curl eklentisi) $api = getenv('MXGATE_API'); // https://API_ADRESINIZ $key = getenv('MXGATE_KEY'); // erişim anahtarı $secret = getenv('MXGATE_SECRET'); // gizli anahtar $ch = curl_init("$api/v1/email/send"); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => [ "Authorization: Bearer $key:$secret", 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'from' => 'Muhasebe <fatura@bildirim.firma.com>', 'to' => ['musteri@example.com'], 'subject' => 'Faturanız hazır', 'text' => 'Faturanız ektedir.', 'html' => '<p>Faturanız ektedir.</p>', 'tags' => ['tur' => 'fatura'], ]), ]); $body = json_decode(curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($status === 202) { echo $body['message_id'], PHP_EOL; // teslim durumunu bu kimlikle sorgularsınız } else { echo "Hata $status: {$body['error']['code']} - {$body['error']['message']}", PHP_EOL; }# Python 3 · pip install requests import os, requests api = os.environ["MXGATE_API"] # https://API_ADRESINIZ key = os.environ["MXGATE_KEY"] # erişim anahtarı secret = os.environ["MXGATE_SECRET"] # gizli anahtar r = requests.post( f"{api}/v1/email/send", headers={"Authorization": f"Bearer {key}:{secret}"}, json={ "from": "Muhasebe <fatura@bildirim.firma.com>", "to": ["musteri@example.com"], "subject": "Faturanız hazır", "text": "Faturanız ektedir.", "html": "<p>Faturanız ektedir.</p>", "tags": {"tur": "fatura"}, }, timeout=30, ) body = r.json() if r.status_code == 202: print(body["message_id"]) # teslim durumunu bu kimlikle sorgularsınız else: print(f"Hata {r.status_code}: {body['error']['code']} - {body['error']['message']}")// Node.js 18+ · ek paket gerekmez (yerleşik fetch) const api = process.env.MXGATE_API; // https://API_ADRESINIZ const key = process.env.MXGATE_KEY; // erişim anahtarı const secret = process.env.MXGATE_SECRET; // gizli anahtar const res = await fetch(`${api}/v1/email/send`, { method: "POST", headers: { Authorization: `Bearer ${key}:${secret}`, "Content-Type": "application/json", }, body: JSON.stringify({ from: "Muhasebe <fatura@bildirim.firma.com>", to: ["musteri@example.com"], subject: "Faturanız hazır", text: "Faturanız ektedir.", html: "<p>Faturanız ektedir.</p>", tags: { tur: "fatura" }, }), }); const body = await res.json(); if (res.status === 202) { console.log(body.message_id); // teslim durumunu bu kimlikle sorgularsınız } else { console.log(`Hata ${res.status}: ${body.error.code} - ${body.error.message}`); }Body fields:from,to,cc,bcc,reply_to(one address or a list),subject,text,html,headers,tags,attachments(filename, base64content,content_type). Instead of these you can sendtemplate+template_data, orrawfor a ready MIME message. -
Query delivery status
For every message sent, the delivery, deferral or rejection of each recipient can be read from the API. Status values:
accepted,delivered,deferred,held,bounced,rejected.DELIVERY STATUS · REST# Tek ileti: alıcı bazında durum curl -H "Authorization: Bearer $MXGATE_KEY:$MXGATE_SECRET" \ "$MXGATE_API/v1/email/messages/$MESSAGE_ID" # Liste: en yeniden eskiye, adrese göre arama curl -H "Authorization: Bearer $MXGATE_KEY:$MXGATE_SECRET" \ "$MXGATE_API/v1/email/messages?limit=50&search=musteri@example.com" # -> {"message_id": "...", "status": "delivered", # "recipients": [{"address": "musteri@example.com", "status": "delivered", # "detail": "250 2.0.0 OK", "updated_at": "..."}]} # status: accepted | delivered | deferred | held | bounced | rejected<?php $api = getenv('MXGATE_API'); $key = getenv('MXGATE_KEY'); $secret = getenv('MXGATE_SECRET'); $messageId = $argv[1]; // gönderimde dönen message_id $ch = curl_init("$api/v1/email/messages/" . rawurlencode($messageId)); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer $key:$secret"], ]); $msg = json_decode(curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($status !== 200) { exit("Hata $status: {$msg['error']['code']}" . PHP_EOL); } foreach ($msg['recipients'] as $r) { // status: accepted | delivered | deferred | held | bounced | rejected echo $r['address'], ' → ', $r['status'], ' ', $r['detail'] ?? '', PHP_EOL; }import os, sys, requests api, key, secret = os.environ["MXGATE_API"], os.environ["MXGATE_KEY"], os.environ["MXGATE_SECRET"] message_id = sys.argv[1] # gönderimde dönen message_id r = requests.get(f"{api}/v1/email/messages/{message_id}", headers={"Authorization": f"Bearer {key}:{secret}"}, timeout=30) msg = r.json() if r.status_code != 200: sys.exit(f"Hata {r.status_code}: {msg['error']['code']}") for rcpt in msg["recipients"]: # status: accepted | delivered | deferred | held | bounced | rejected print(rcpt["address"], "→", rcpt["status"], rcpt.get("detail", ""))const { MXGATE_API: api, MXGATE_KEY: key, MXGATE_SECRET: secret } = process.env; const messageId = process.argv[2]; // gönderimde dönen message_id const res = await fetch(`${api}/v1/email/messages/${encodeURIComponent(messageId)}`, { headers: { Authorization: `Bearer ${key}:${secret}` }, }); const msg = await res.json(); if (res.status !== 200) { console.log(`Hata ${res.status}: ${msg.error.code}`); process.exit(1); } for (const r of msg.recipients) { // status: accepted | delivered | deferred | held | bounced | rejected console.log(r.address, "→", r.status, r.detail ?? ""); } -
Receive events by webhook
Instead of polling the status you can have every event reported to your address. You define the webhook address in the client area. Every request is signed with the
X-MXGate-Signatureheader; do not trust the body without verifying the signature.WEBHOOK SIGNATURE VERIFICATION<?php // Her olay adresinize POST edilir. Gövde: Amazon SES olay kaydı. // Başlık: X-MXGate-Signature: t=<unix zamanı>,v1=<hex HMAC-SHA256(imza anahtarı, "<t>.<ham gövde>")> function mxgate_webhook(string $signatureHeader, string $rawBody, string $signingSecret): array { parse_str(str_replace(',', '&', $signatureHeader), $parts); // t=…,v1=… $mac = hash_hmac('sha256', ($parts['t'] ?? '') . '.' . $rawBody, $signingSecret); if (!hash_equals($mac, $parts['v1'] ?? '') || abs(time() - (int) ($parts['t'] ?? 0)) > 300) { return [401, '']; } $event = json_decode($rawBody, true); if ($event['eventType'] === 'WebhookVerification') { // doğrulama: yanıt gövdesinde HMAC-SHA256(imza anahtarı, token) değerini (hex) döndürün return [200, hash_hmac('sha256', $event['token'], $signingSecret)]; } $mid = $event['mail']['messageId']; switch ($event['eventType']) { case 'Delivery': error_log("$mid teslim edildi: " . implode(', ', $event['delivery']['recipients'])); break; case 'Bounce': foreach ($event['bounce']['bouncedRecipients'] as $r) { error_log("$mid geri döndü: {$r['emailAddress']} ({$event['bounce']['bounceType']})"); } break; case 'DeliveryDelay': error_log("$mid erteleniyor"); break; } return [200, '']; // 2xx dışındaki yanıt 24 saat boyunca yeniden denenir } // Kullanım (webhook adresinizdeki dosya): [$status, $body] = mxgate_webhook( $_SERVER['HTTP_X_MXGATE_SIGNATURE'] ?? '', file_get_contents('php://input'), // ham gövde: json_decode edilmiş hali DEĞİL getenv('MXGATE_WEBHOOK_SECRET') ); http_response_code($status); echo $body;# Her olay adresinize POST edilir. Gövde: Amazon SES olay kaydı. # Başlık: X-MXGate-Signature: t=<unix zamanı>,v1=<hex HMAC-SHA256(imza anahtarı, "<t>.<ham gövde>")> import hashlib, hmac, json, time def handle(headers, raw_body: bytes, signing_secret: str): parts = dict(p.split("=", 1) for p in headers["X-MXGate-Signature"].split(",")) mac = hmac.new(signing_secret.encode(), parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest() if not hmac.compare_digest(mac, parts["v1"]) or abs(time.time() - int(parts["t"])) > 300: return 401 event = json.loads(raw_body) if event["eventType"] == "WebhookVerification": # doğrulama: yanıt gövdesinde HMAC-SHA256(imza anahtarı, token) değerini (hex) döndürün return 200, hmac.new(signing_secret.encode(), event["token"].encode(), hashlib.sha256).hexdigest() mid = event["mail"]["messageId"] if event["eventType"] == "Delivery": print(mid, "teslim edildi", event["delivery"]["recipients"], event["delivery"]["smtpResponse"]) elif event["eventType"] == "Bounce": for r in event["bounce"]["bouncedRecipients"]: print(mid, "geri döndü", r["emailAddress"], event["bounce"]["bounceType"], r["diagnosticCode"]) elif event["eventType"] == "DeliveryDelay": print(mid, "erteleniyor", event["deliveryDelay"]["delayedRecipients"]) return 200 # 2xx dışındaki yanıt 24 saat boyunca yeniden denenir// Her olay adresinize POST edilir. Gövde: Amazon SES olay kaydı. // Başlık: X-MXGate-Signature: t=<unix zamanı>,v1=<hex HMAC-SHA256(imza anahtarı, "<t>.<ham gövde>")> import { createHmac, timingSafeEqual } from "node:crypto"; import { createServer } from "node:http"; export function handle(signatureHeader, rawBody, signingSecret) { const parts = Object.fromEntries(signatureHeader.split(",").map((p) => p.split(/=(.*)/s).slice(0, 2))); const mac = createHmac("sha256", signingSecret).update(`${parts.t}.`).update(rawBody).digest("hex"); const ok = mac.length === (parts.v1 ?? "").length && timingSafeEqual(Buffer.from(mac), Buffer.from(parts.v1)); if (!ok || Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return [401, ""]; const event = JSON.parse(rawBody); if (event.eventType === "WebhookVerification") { // doğrulama: yanıt gövdesinde HMAC-SHA256(imza anahtarı, token) değerini (hex) döndürün return [200, createHmac("sha256", signingSecret).update(event.token).digest("hex")]; } const mid = event.mail.messageId; if (event.eventType === "Delivery") console.log(mid, "teslim edildi", event.delivery.recipients); else if (event.eventType === "Bounce") for (const r of event.bounce.bouncedRecipients) console.log(mid, "geri döndü", r.emailAddress, event.bounce.bounceType); else if (event.eventType === "DeliveryDelay") console.log(mid, "erteleniyor"); return [200, ""]; // 2xx dışındaki yanıt 24 saat boyunca yeniden denenir } // Kullanım: ham gövdeyi (Buffer) okuyun; JSON'a çevrilmiş halini DEĞİL createServer((req, res) => { const chunks = []; req.on("data", (c) => chunks.push(c)); req.on("end", () => { const [status, body] = handle(req.headers["x-mxgate-signature"] ?? "", Buffer.concat(chunks), process.env.MXGATE_WEBHOOK_SECRET); res.writeHead(status).end(body); }); }).listen(process.env.PORT ?? 8080);Events:Send(accepted),Delivery,Bounce,DeliveryDelay. The body is in the Amazon SES event record format. A non-2xx answer or a 10-second timeout is retried with growing delays for 24 hours; after 50 consecutive failures the webhook is paused. A send refused for content or policy produces no event; the API call itself returns the error.
Sending with the AWS SDK: only the endpoint and the key change
In your application that uses Amazon SES v2, give your account’s API address as the endpoint and use your MXGate key. Authentication is the same (AWS Signature V4) and no AWS account is needed. The region name can be any value; it is only part of the signature.
import boto3 # pip install boto3
ses = boto3.client(
"sesv2",
endpoint_url="https://API_ADRESINIZ",
region_name="eu-central-1", # herhangi bir değer; yalnız imzanın parçası
aws_access_key_id="MXGA................",
aws_secret_access_key="........................................",
)
r = ses.send_email(
FromEmailAddress="Muhasebe <fatura@bildirim.firma.com>",
Destination={"ToAddresses": ["musteri@example.com"]},
Content={"Simple": {
"Subject": {"Data": "Faturanız hazır"},
"Body": {"Text": {"Data": "Faturanız ektedir."},
"Html": {"Data": "<p>Faturanız ektedir.</p>"}},
"Attachments": [{"FileName": "fatura.pdf",
"ContentType": "application/pdf",
"RawContent": open("fatura.pdf", "rb").read()}],
}},
)
print(r["MessageId"])// npm install @aws-sdk/client-sesv2
import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
const ses = new SESv2Client({
endpoint: "https://API_ADRESINIZ",
region: "eu-central-1",
credentials: { accessKeyId: "MXGA................", secretAccessKey: "........" },
});
const r = await ses.send(new SendEmailCommand({
FromEmailAddress: "Muhasebe <fatura@bildirim.firma.com>",
Destination: { ToAddresses: ["musteri@example.com"] },
Content: { Simple: {
Subject: { Data: "Faturanız hazır" },
Body: { Html: { Data: "<p>Faturanız ektedir.</p>" } },
} },
}));
console.log(r.MessageId);<?php
require 'vendor/autoload.php'; // composer require aws/aws-sdk-php
use Aws\SesV2\SesV2Client;
$ses = new SesV2Client([
'version' => 'latest',
'region' => 'eu-central-1',
'endpoint' => 'https://API_ADRESINIZ',
'credentials' => ['key' => 'MXGA................', 'secret' => '........'],
]);
$r = $ses->sendEmail([
'FromEmailAddress' => 'Muhasebe <fatura@bildirim.firma.com>',
'Destination' => ['ToAddresses' => ['musteri@example.com']],
'Content' => ['Simple' => [
'Subject' => ['Data' => 'Faturanız hazır'],
'Body' => ['Html' => ['Data' => '<p>Faturanız ektedir.</p>']],
]],
]);
echo $r['MessageId'];export AWS_ACCESS_KEY_ID=MXGA................
export AWS_SECRET_ACCESS_KEY=........................................
aws sesv2 send-email --endpoint-url https://API_ADRESINIZ --region eu-central-1 \
--from-email-address fatura@bildirim.firma.com \
--destination ToAddresses=musteri@example.com \
--content '{"Simple":{"Subject":{"Data":"Deneme"},"Body":{"Text":{"Data":"Merhaba"}}}}'Supported operations
SendEmail (Simple, Raw and Template content), SendBulkEmail (50 messages per call), GetAccount, GetMessageInsights, email templates, the suppression list and read-only identity queries.
Differences from Amazon SES
At most 50 recipients and 40 MB per message. The Message-ID header is written by the system and equals the returned MessageId. In Raw content the Bcc header is removed. Fields such as IdentityArn and EndpointId are accepted but not used.
Tags and events
ConfigurationSetName and EmailTags are stored and carried in webhook events. Event bodies are in the Amazon SES event record format, so you can keep your existing event handler.
Bulk sending with templates and pulling events from the API
Save a template once, send to each recipient with their own data
send-bulk takes up to 50 messages in one call and returns a separate result for each: accepted, or failed with an error code.
# 1) Şablonu bir kez kaydedin ({{ad}} gibi değişkenlerle)
curl -X PUT "$MXGATE_API/v1/email/templates/hosgeldin" \
-H "Authorization: Bearer $MXGATE_KEY:$MXGATE_SECRET" -H "Content-Type: application/json" \
-d '{"subject": "Hoş geldiniz {{ad}}", "html": "<p>Merhaba {{ad}}, hesabınız hazır.</p>", "text": "Merhaba {{ad}}, hesabınız hazır."}'
# 2) Tek istekte her alıcıya kendi verisiyle gönderin (çağrı başına en çok 50 ileti)
curl -X POST "$MXGATE_API/v1/email/send-bulk" \
-H "Authorization: Bearer $MXGATE_KEY:$MXGATE_SECRET" -H "Content-Type: application/json" \
-d '{
"from": "Destek <destek@bildirim.firma.com>",
"template": "hosgeldin",
"messages": [
{"to": "ayse@example.com", "template_data": {"ad": "Ayşe"}},
{"to": "mehmet@example.com", "template_data": {"ad": "Mehmet"}}
]
}'If you cannot run a webhook, pull events in order
You store the next_after value from the last answer and pass it in the next request. Events are kept for 7 days; for older ones use the message status endpoint. At most 60 requests per minute are allowed.
# Sunucu açmadan olayları çekin: son yanıttaki next_after değerini saklayıp bir sonraki istekte verin.
import os, time, requests # pip install requests
api, key, secret = os.environ["MXGATE_API"], os.environ["MXGATE_KEY"], os.environ["MXGATE_SECRET"]
after = 0 # kalıcı bir yerde saklayın
while True:
r = requests.get(f"{api}/v1/email/events", params={"after": after, "limit": 100},
headers={"Authorization": f"Bearer {key}:{secret}"}).json()
for e in r["events"]: # e["event"]: webhook'a giden kayıtla aynı gövde
print(e["id"], e["type"], e["message_id"], e["recipient"], e["time"])
after = r["next_after"]
if not r["has_more"]:
time.sleep(30)
# Süzgeçler: types=Delivery,Bounce message_id=<message_id>Idempotency-Key header to the REST request (1–255 characters). A request repeated with the same key and body within 24 hours does not send the email again; the answer carries an Idempotent-Replay: true header. The same key with a different body returns 422 idempotency_key_reused, and 409 request_in_progress while the first request is still being processed.Error responses and codes
REST errors have the form {"error": {"code": "…", "message": "…"}, "request_id": "…"}; quote the request_id in a support ticket. The SES SDK reports the same conditions by exception name.
| HTTP | REST code | SES error name | Meaning |
|---|---|---|---|
400 | bad_request | BadRequestException | Invalid request body or unsupported operation |
401 | unauthorized | InvalidSignatureException | Wrong or paused key; with SES the system clock may be off by more than 5 minutes |
403 | forbidden | AccessDeniedException | The key is not allowed from this IP address or for REST |
403 | domain_not_allowed | AccessDeniedException | The key is locked to a different sender domain |
422 | message_rejected | MessageRejected | Sender domain not verified or not registered (the answer names the missing record), content rejected, or recipient not accepted |
422 | domain_suspended | MessageRejected | The domain is paused because of the plan limit; choose your active domains in the panel |
429 | quota_exceeded | LimitExceededException | The hourly, daily or monthly sending allowance is used up |
429 | rate_limited | TooManyRequestsException | The per-second request limit was exceeded; retry after a short wait (the SDK retries by itself) |
403 | sending_paused | SendingPausedException | Sending is paused for the account |
404 | not_found | NotFoundException | The record was not found |
503 | unavailable | ServiceUnavailableException | Temporary problem; retry |
The HTTP statuses are for REST; on the SES-compatible endpoint status codes follow Amazon SES. On 429 and 503 retry after a short wait; for the other 4xx answers do not retry without fixing the request.
Sending from an unverified domain: which record is missing?
Sending from a domain opens once both its DKIM and SPF records are verified. When a send is refused, the answer names the missing record both in the message and under error.details.domains; on the SES-compatible endpoint the error name stays MessageRejected and the same explanation is in the message text.
{
"error": {
"code": "message_rejected",
"message": "Email address is not verified. The following identities failed the check: fatura@bildirim.firma.com (DKIM and SPF records not verified)",
"details": {
"domains": [
{ "domain": "bildirim.firma.com", "reason": "not_verified", "missing": ["dkim", "spf"] }
]
}
},
"request_id": "41e555f8-49a1-407e-a5de-30720528d734"
}reason | missing | What to do |
|---|---|---|
not_verified | dkim, spf | Enter the missing record shown in the client area into your DNS, then press “Check DNS”. |
verification_lost | dkim, spf | The domain was verified before and the record has disappeared from DNS. Restore it and sending reopens on its own. |
unknown_domain | — | The domain of your sender address is not defined on your account; add it in the client area. |
domain_disabled | — | The domain has been disabled; contact support. |
Questions about email API integration
Which programming languages are supported?
The REST API works from any language that can send an HTTPS request. This page has examples for curl, PHP, Python and Node.js that were run and verified. Thanks to the Amazon SES v2 compatible endpoint, in languages with an AWS SDK (Python, JavaScript, PHP and others) you can also send by changing only the endpoint and the key.
If I send the same request twice, is the email sent twice?
Not if you use the Idempotency-Key header. A request repeated with the same key and the same body within 24 hours does not send the email again and returns the first answer. To retry a timed-out request safely, give every send a unique key (an order number, for example).
What does the API return when the monthly limit is reached?
The REST API returns a quota_exceeded error with status 429; the SES SDK raises LimitExceededException. Sending reopens at the start of the month, or within 30 seconds after you upgrade your plan.
Can I use the API with Postman or a code generator?
Yes. A machine-readable description of the REST endpoints (OpenAPI) is published at /v1/email/openapi.json on your account’s API address; you can import it into Postman or generate client code from it.
Are there complaint, open and click events?
No. The reported events are send acceptance, delivery, bounce and delay. There is no complaint, open or click tracking.
Get your key and send the first email
Plans start at $19 USD a month; your API address and key arrive in your client area after ordering. If you get stuck, write to our technical team.