使用SendGrid Marketing Campaigns API创建Single Sends遇多问题求助
SendGrid新版Marketing Campaigns API问题解决方案
问题1:携带send_at: "now"时JSON解析失败
错误原因:手动拼接JSON字符串时,若变量(如$name)包含引号、换行等特殊字符,会直接破坏JSON结构,导致解析失败;同时手动转对象的方式也容易引入格式问题。
解决方法:
改用数组构建请求体,让SDK自动处理JSON序列化,避免手动拼接的风险:
$sg = new \SendGrid($_ENV['SENDGRID_API_KEY']); $request_body = [ "name" => $name, "send_at" => "now", "send_to" => ["list_ids" => ["222418c1-4360-47ed-xxxx-xxxxxxxx"]], "email_config" => [ "subject" => "hello", "html_content" => "hi there", "use_default_unsubscribe_footer" => true ] ]; try { $response = $sg->client->marketing()->singlesends()->post($request_body); echo "<br><br><br>"; echo '<pre>'; print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; echo '</pre>'; return true; } catch (Exception $ex) { echo 'Caught exception: ' . $ex->getMessage(); return false; }
问题2:草稿状态Single Send调度发送时间
创建草稿后,调用Single Send的更新接口(PUT请求),传入ISO 8601格式的send_at参数即可完成调度:
$single_send_id = "你的草稿Single Send ID"; $schedule_body = [ "send_at" => "2024-12-31T12:00:00Z" // 替换为目标发送时间 ]; try { $response = $sg->client->marketing()->singlesends()->_($single_send_id)->put($schedule_body); // 处理响应逻辑 } catch (Exception $ex) { echo 'Caught exception: ' . $ex->getMessage(); }
问题3:自动插入默认退订链接,避免custom_unsubscribe URL要求
SendGrid不会自动插入默认退订链接,需显式开启配置:
- 在
email_config中添加use_default_unsubscribe_footer: true参数,不要设置custom_unsubscribe_url,SendGrid就会自动插入官方默认的退订链接,同时不会再触发custom_unsubscribe的必填校验。 - 配置示例见问题1的请求体代码。
内容的提问来源于stack exchange,提问作者Lakhvinder Dhillon
相关产品推荐
相关产品推荐

