Mailtrap API - Cannot send emails - "Unauthorized" API error

Viewed 39

I am using Mailtrap's SMTP to send my development/test e-mails to a fake inbox.

Their SMTP server feature works well, but I'm now trying to implement their API v2 instead.

Every time I hit the https://send.api.mailtrap.io/api/send endpoint, I keep getting the following error:

{"errors":["Unauthorized"]}

More info

  • I have a Paid account and generated an API Token which has full Admin rights
  • Only the send.api.mailtrap.io/api/send endpoint fails, other endpoints such as mailtrap.io/accounts are working
  • I am getting the same error whether I use their API Doc Request testing tool or my code
  • I am getting the same error message with their API v1

cURL request used (from their API docs)

curl -X POST "https://send.api.mailtrap.io/api/send" \
 -H "Accept: application/json" \
 -H "Api-Token: xxxxxxxxxxxxxxxxxxxxxxxxx" \
 -H "Content-Type: application/json" \
 -d '{"to":[{"email":"john_doe@example.com","name":"John Doe"}],"from":{"email":"sales@example.com","name":"Example Sales Team"},"subject":"Your Example Order Confirmation","html":"<p>Congratulations on your order no. <strong>1234</strong>.</p>"}'

Similar cURL request via PHP (same error message)

<?php

$post = [];
$post['to'] = 'test@test.com';
$post['from'] = ['name' => 'Test', 'email' => 'test@test.com'];
$post['subject'] = 'Test';
$post['html'] = '<h2>This is a test</h2><p>It works!</p>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://send.api.mailtrap.io/api/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Api-Token: xxxxxxxxxxxxxxxxxxxxxxxxx']);
$result = curl_exec($ch);

print_r($result);
echo "\n";
2 Answers

I finally found the answer, here are my conclusions:

  • As of Today (Sep 2022), Mailtrap's Sending API cannot be used to send e-mails to your Mailtrap Sandbox (i.e. Fake Inbox). It can only be used to send real/production e-mails, to real users.

  • If your Mailtrap account is older than a year, you will most likely be missing the "Send API" section in your account and only see the "API" section. The only solution to address that was to create a new account.

  • If you still plan to use Mailtrap's Sending API (to send production e-mails), you will need to reach out to Support for some pre-configuration (This is not mentioned in the documentation) otherwise you will receive "Forbidden" from the API, without any additional details.

Does it mean we needs to write separate logic for dev/staging (using SMTP) and for prod (using API) in our apps? Sounds really strange.

Related