smtpmailtrap

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


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

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";

Solution

  • I finally found the answer, here are my conclusions: