使用Mailchimp API批量发送个性化邮件失败问题排查
Mailchimp邮件发送代码问题分析与修正
现有代码的核心错误
- API端点与请求逻辑错误:
- 创建Campaign时,
UrlFetchApp.fetch(endpoint + '/campaigns', options)未传递请求体data,无法生成有效Campaign。 - 发送Campaign的端点格式错误,正确路径应为
https://us2.api.mailchimp.com/3.0/campaigns/{campaign_id}/actions/send,必须基于已创建的Campaign ID发起请求,而非通用的/campaigns/actions/send。
- 创建Campaign时,
- 数据格式错误:
recipients处理逻辑错误:代码将整个收件人数组直接赋值给email_address,正确做法是针对每个收件人创建独立对象,或通过受众细分筛选目标用户(你的Campaign1已包含大量订阅邮箱,更适合用细分规则)。templateId传入了数组类型,实际需传入单个字符串ID(即"237173"而非["237173"])。
- 请求配置缺失:
options中未包含payload字段,需将data转为JSON字符串后加入请求选项,否则API无法接收请求体数据。
个性化内容实现思路
要为每个收件人动态替换模板区块内容,最高效的方式是:
- 在Mailchimp受众列表中添加自定义合并字段(比如命名为
ORDER_ID)。 - 将
block_content中的对应值批量更新到每个收件人的ORDER_ID字段中。 - 在
template1的目标区块中插入合并标签*|ORDER_ID|*,Mailchimp会自动为每个收件人替换为对应值。
修正后的完整代码
function sendMailchimpEmail() { // 配置参数 var apiKey = 'YOUR_API_KEY'; var endpoint = 'https://us2.api.mailchimp.com/3.0/'; var listId = 'YOUR_LIST_ID'; // 你的Campaign1关联的受众列表ID var templateId = '237173'; var recipients = ['1@gmail.com', 'b@gmail.com', 'c@gmail.com']; var blockContent = ["<h2>HR1213675</h2>","<h2>8923783ER</h2>","<h2>JUIYE34324</h2>"]; // 1. 批量更新收件人的合并字段(ORDER_ID) var updateOptions = { method: 'POST', contentType: 'application/json', headers: { Authorization: 'apikey ' + apiKey }, payload: JSON.stringify({ members: recipients.map((email, index) => ({ email_address: email, status_if_new: 'subscribed', merge_fields: { ORDER_ID: blockContent[index] } })), update_existing: true }) }; UrlFetchApp.fetch(endpoint + 'lists/' + listId, updateOptions); // 2. 创建个性化Campaign var createCampaignOptions = { method: 'POST', contentType: 'application/json', headers: { Authorization: 'apikey ' + apiKey }, payload: JSON.stringify({ type: 'regular', recipients: { list_id: listId, segment_opts: { match: 'any', conditions: [ { condition_type: 'EmailAddress', field: 'email_address', op: 'in', value: recipients } ] } }, settings: { subject_line: '你的邮件主题', from_name: '发件人名称', reply_to: 'reply@yourdomain.com' }, template: { id: templateId } }) }; var createResponse = UrlFetchApp.fetch(endpoint + 'campaigns', createCampaignOptions); var campaignData = JSON.parse(createResponse.getContentText()); var campaignId = campaignData.id; // 3. 发送Campaign var sendOptions = { method: 'POST', contentType: 'application/json', headers: { Authorization: 'apikey ' + apiKey } }; UrlFetchApp.fetch(endpoint + 'campaigns/' + campaignId + '/actions/send', sendOptions); }
注意事项
- 替换
YOUR_API_KEY、YOUR_LIST_ID、发件人信息等为实际值。 - 确保模板
template1中已添加*|ORDER_ID|*合并标签,放置在需要动态替换的区块位置。 - 若模板有指定的区块ID,也可在
template.sections中直接指定区块替换内容,比如'your_block_id': '*|ORDER_ID|*'。
内容的提问来源于stack exchange,提问作者Code Guy
相关产品推荐
相关产品推荐

