This use case demonstrates how to personalize emails using merge tags (also known as merge variables) with the Mailchimp Transactional (Mandrill) API.
Merge tags are placeholders in your email content that get replaced with actual data when the email is sent. They enable personalization at scale.
- PHP 7.4+
- Composer
- Mandrill API key
- Configured
.envfile
<?php
require_once __DIR__ . '/vendor/autoload.php';
$mailchimp = new \MailchimpTransactional\ApiClient();
$mailchimp->setApiKey($_ENV['MANDRILL_API_KEY']);
$message = [
'html' => '
<h1>Welcome {{fname}}!</h1>
<p>Thanks for joining {{company_name}}.</p>
<p>Your membership level: {{membership_level}}</p>
',
'subject' => 'Welcome to {{company_name}}, {{fname}}!',
'from_email' => 'sender@example.com',
'from_name' => 'Company Name',
'to' => [
[
'email' => 'recipient@example.com',
'name' => 'John Smith',
'type' => 'to'
]
],
// Global merge vars apply to all recipients
'global_merge_vars' => [
['name' => 'company_name', 'content' => 'Acme Corp'],
['name' => 'membership_level', 'content' => 'Premium']
],
// Per-recipient merge vars
'merge_vars' => [
[
'rcpt' => 'recipient@example.com',
'vars' => [
['name' => 'fname', 'content' => 'John']
]
]
],
'merge_language' => 'handlebars'
];
$result = $mailchimp->messages->send(['message' => $message]);Apply to all recipients in the email:
'global_merge_vars' => [
['name' => 'company_name', 'content' => 'Acme Corp']
]Different values per recipient:
'merge_vars' => [
[
'rcpt' => 'john@example.com',
'vars' => [
['name' => 'fname', 'content' => 'John']
]
],
[
'rcpt' => 'jane@example.com',
'vars' => [
['name' => 'fname', 'content' => 'Jane']
]
]
]handlebars- Use{{variable_name}}syntax (recommended)mailchimp- Use*|VARIABLE_NAME|*syntax
- Set
merge_languageto specify syntax - Use
global_merge_varsfor values shared across all recipients - Use
merge_varsfor per-recipient personalization - Merge tags work in subject, HTML body, and text body