2025年12月13日/ 浏览 20
在营销自动化场景中,第三方邮件模板服务(如Mailchimp、SendGrid)能显著提升邮件触达效率。本文以Mailchimp为例,手把手教你通过PHP实现模板调用,覆盖从接口认证到动态内容渲染的全流程。
获取API Key
登录Mailchimp后台,进入「Account」→「Extras」→「API Keys」,生成专属API密钥。密钥格式通常为{dc}-{随机字符串},{dc}代表数据中心编号(如us12)。
安装HTTP客户端
推荐使用Guzzle等PHP HTTP库简化请求:
bash
composer require guzzlehttp/guzzle
Mailchimp的REST API遵循标准HTTP协议,需在请求头中传递认证信息。以下是获取账户信息的示例:
"https://{$dataCenter}.api.mailchimp.com/3.0/",
'headers' => [
'Authorization' => 'apikey ' . $apiKey,
'Content-Type' => 'application/json'
]
]);
// 获取账户信息
$response = $client->get('account');
echo $response->getBody();
?>
Mailchimp的模板接口位于/templates/{template_id}。假设已创建ID为500的模板,需按以下步骤调用:
加载模板
php
$templateId = 500;
$response = $client->get("templates/{$templateId}");
$template = json_decode($response->getBody(), true);
动态内容替换
通过template_content字段插入变量(如用户名、优惠码):
php
$mergedContent = str_replace(
['{{name}}', '{{coupon}}'],
['张三', 'OFF50'],
$template['html']
);
结合Mailchimp的Campaign API发送最终邮件:
$campaignData = [
'type' => 'regular',
'recipients' => ['list_id' => 'your-list-id'],
'settings' => [
'subject_line' => '专属优惠通知',
'from_name' => '品牌客服',
'reply_to' => 'support@example.com'
]
];
// 创建Campaign
$response = $client->post('campaigns', ['json' => $campaignData]);
$campaignId = json_decode($response->getBody())->id;
// 设置邮件内容
$client->put("campaigns/{$campaignId}/content", [
'json' => ['html' => $mergedContent]
]);
// 立即发送
$client->post("campaigns/{$campaignId}/actions/send");
429状态码并重试。 php
$response->getStatusCode();
$response->getHeaders(); 通过上述步骤,你已掌握PHP调用Mailchimp模板的核心流程。实际应用中,可进一步封装为Service类,结合队列系统实现异步发送。其他服务商(如SendGrid、Amazon SES)的接口设计类似,只需调整认证方式和端点路径即可快速迁移。