Skip to content
KVKK & GDPR Compliant Turkey Data Center 24/7 Technical Support destek@mxgate.com.tr
New: IP reputation monitoring is now free on every plan Start your 1-month free trial →
INTEGRATION GUIDE · EMAIL API

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.

Authentication
Authorization: Bearer key:secret (REST) or AWS Signature V4 (SES SDK)
Format
JSON over HTTPS; the answer is 202 with a message ID
Limits
50 recipients per message, at most 40 MB (attachments included), 10 requests per second
Events
Signed webhooks or pulling from the API; message logs for 90 days
GETTING STARTED

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.

  1. 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_API is your account’s API address (shown in your client area), MXGATE_KEY the access key and MXGATE_SECRET the 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.
  2. 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 as notify.yourcompany.com for the API.
  3. 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 · REST
    curl -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"}
    Body fields: from, to, cc, bcc, reply_to (one address or a list), subject, text, html, headers, tags, attachments (filename, base64 content, content_type). Instead of these you can send template + template_data, or raw for a ready MIME message.
  4. 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
  5. 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-Signature header; 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;
    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.
AMAZON SES COMPATIBLE

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.

SEND A MESSAGE · SES V2
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"])

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.

GOING FURTHER

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.

TEMPLATE + BULK SEND · REST
# 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.

PULLING EVENTS · REST
# 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>
Preventing duplicate sends: add an 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 HANDLING

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.

HTTPREST codeSES error nameMeaning
400bad_requestBadRequestExceptionInvalid request body or unsupported operation
401unauthorizedInvalidSignatureExceptionWrong or paused key; with SES the system clock may be off by more than 5 minutes
403forbiddenAccessDeniedExceptionThe key is not allowed from this IP address or for REST
403domain_not_allowedAccessDeniedExceptionThe key is locked to a different sender domain
422message_rejectedMessageRejectedSender domain not verified or not registered (the answer names the missing record), content rejected, or recipient not accepted
422domain_suspendedMessageRejectedThe domain is paused because of the plan limit; choose your active domains in the panel
429quota_exceededLimitExceededExceptionThe hourly, daily or monthly sending allowance is used up
429rate_limitedTooManyRequestsExceptionThe per-second request limit was exceeded; retry after a short wait (the SDK retries by itself)
403sending_pausedSendingPausedExceptionSending is paused for the account
404not_foundNotFoundExceptionThe record was not found
503unavailableServiceUnavailableExceptionTemporary 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.

REST ANSWER · 422
{
  "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"
}
reasonmissingWhat to do
not_verifieddkim, spfEnter the missing record shown in the client area into your DNS, then press “Check DNS”.
verification_lostdkim, spfThe 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.
FAQ

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.

See the plans Write to the technical team
Last updated: