Testing the Mailgun API with test mode and the sandbox domain

Mailgun's API looks a little old-fashioned next to JSON APIs: Basic auth with the username api, and a form body instead of JSON. It's straightforward once you know that, and it has a test mode that accepts a message without delivering it.

Step 1: Environment

VariableValue
baseUrlhttps://api.mailgun.net/v3 (EU: https://api.eu.mailgun.net/v3)
mailgunKeyyour API key, marked as secret
mailgunDomainmg.example.com, or your sandbox….mailgun.org domain
toEmaila test inbox

Authorization: Basic auth, username api, password {{mailgunKey}}.

The sandbox domain every account gets only delivers to authorized recipients you've added in Mailgun. That's a fine safety net for tests.

Step 2: Send in test mode

HTTP
POST {{baseUrl}}/{{mailgunDomain}}/messages
Content-Type: application/x-www-form-urlencoded

from=API tests <tests@{{mailgunDomain}}>&to={{toEmail}}&subject=Test mode&text=Hello&o:testmode=yes

In Requestarium, use the x-www-form-urlencoded body type and add the fields as rows; the encoding is done for you.

JavaScript
pm.test('queued', () => {
  pm.expect(pm.response.code).to.equal(200);
  const body = pm.response.json();
  pm.expect(body.message).to.include('Queued');
  pm.expect(body.id).to.match(/^<.+>$/);
  pm.environment.set('mailgunMessageId', body.id);
});

The id is the message id in angle brackets. Mailgun accepted the message and, in test mode, dropped it instead of delivering.

Step 3: Tags and variables

Output
o:tag=api-test
v:order-id=1234
h:[email protected]

o: fields are options, v: fields are custom variables that come back in webhooks and events, and h: fields add headers. Tagging test traffic with o:tag=api-test makes it easy to filter out in Mailgun's logs.

Step 4: Check the event

HTTP
GET {{baseUrl}}/{{mailgunDomain}}/events?message-id={{mailgunMessageIdBare}}&limit=10

Events take a few seconds to appear, and the message-id filter takes the id without the angle brackets. Strip them in the send request's script:

JavaScript
pm.environment.set('mailgunMessageIdBare', pm.response.json().id.replace(/[<>]/g, ''));

If this check is part of a run, add a delay before it, or treat it as a separate monitoring request. See testing async jobs for polling patterns.

Step 5: The errors

StatusCause
400missing from, to or a body, or an invalid address
401wrong key, or the wrong region for the account
403the sandbox domain and an unauthorized recipient
404the domain doesn't exist in this account or region
JavaScript
// "Send without to": expected failure
pm.test('missing recipient refused', () => {
  pm.expect(pm.response.code).to.equal(400);
  pm.expect(pm.response.json().message).to.be.ok;
});