This use case demonstrates how to send a basic transactional email to a single recipient using the Mailchimp Transactional (Mandrill) API with PHP.
- PHP 7.4+
- Composer
- Mandrill API key
- Configured
.envfile
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$mailchimp = new \MailchimpTransactional\ApiClient();
$mailchimp->setApiKey($_ENV['MANDRILL_API_KEY']);
$message = [
'html' => '<p>Hello! This is a test email.</p>',
'text' => 'Hello! This is a test email.',
'subject' => 'Hello World',
'from_email' => 'sender@example.com',
'from_name' => 'Sender Name',
'to' => [
[
'email' => 'recipient@example.com',
'name' => 'Recipient Name',
'type' => 'to'
]
]
];
try {
$result = $mailchimp->messages->send(['message' => $message]);
print_r($result);
} catch (\MailchimpTransactional\ApiException $e) {
echo "Error: " . $e->getMessage();
}- API Client Initialization: Create a new
ApiClientand set your API key - Message Structure: The message array contains all email details
- Recipient Type: Use
'type' => 'to'for primary recipients (also supportsccandbcc) - Error Handling: Catch
ApiExceptionfor API-related errors
A successful response returns an array:
[
[
'email' => 'recipient@example.com',
'status' => 'sent',
'_id' => 'abc123...',
'reject_reason' => null
]
]