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
| Variable | Value |
|---|---|
baseUrl | https://api.mailgun.net/v3 (EU: https://api.eu.mailgun.net/v3) |
mailgunKey | your API key, marked as secret |
mailgunDomain | mg.example.com, or your sandbox….mailgun.org domain |
toEmail | a 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
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=yesIn Requestarium, use the x-www-form-urlencoded body type and add the fields as rows; the encoding is done for you.
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
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
GET {{baseUrl}}/{{mailgunDomain}}/events?message-id={{mailgunMessageIdBare}}&limit=10Events 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:
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
| Status | Cause |
|---|---|
400 | missing from, to or a body, or an invalid address |
401 | wrong key, or the wrong region for the account |
403 | the sandbox domain and an unauthorized recipient |
404 | the domain doesn't exist in this account or region |
// "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;
});