PHP表单提交触发cURL调用Courier API发邮件失败如何解决
表单提交调用Courier API发邮件失败排查修复方案
一、现有代码核心错误
- 认证头配置错误:你把Authorization认证头放到了POST请求体中,Courier API要求将
Bearer {token}格式的认证信息放在请求头里,需要通过CURLOPT_HTTPHEADER参数配置,不能放在POSTFIELDS中。 - 请求体格式错误:Courier /send接口要求提交JSON格式的请求体,你现在提交的是form-data格式的数组,且profile字段手动拼接JSON字符串的方式也不符合要求。
- 缺失错误校验逻辑:没有判断cURL执行是否出错,也没有打印API返回的响应内容,无法定位是请求错误、权限错误还是参数错误。
- 表单参数未使用:所有收件人信息都是硬编码的,没有读取表单提交的邮箱、姓名等参数,即便请求成功也不会发给表单填写的收件人。
二、修复后的完整代码
<?php $result = ''; if(isset($_POST['submit'])){ // 读取表单提交的参数 $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $email = $_POST['email']; $message = $_POST['message']; $auth_token = '替换为你的Courier Auth Token'; $event_id = 'personalized-welcome-email'; $ch = curl_init(); // 构造请求体 $postData = [ 'event' => $event_id, 'recipient' => uniqid(), // 可以自定义收件人ID,也可以直接用邮箱作为唯一标识 'profile' => [ 'email' => $email ], // 传递模板变量,对应你在Courier后台设置的模板参数 'data' => [ 'first_name' => $first_name, 'last_name' => $last_name, 'message' => $message ] ]; $curlConfig = array( CURLOPT_URL => "https://api.courier.com/send", CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, // 配置请求头:认证信息+声明JSON格式 CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $auth_token, 'Content-Type: application/json' ], // 把请求体转为JSON字符串 CURLOPT_POSTFIELDS => json_encode($postData) ); curl_setopt_array($ch, $curlConfig); $response = curl_exec($ch); // 捕获cURL错误 if(curl_errno($ch)){ $result = 'cURL错误:' . curl_error($ch); }else{ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $result = '请求状态码:' . $httpCode . ',响应内容:' . $response; } curl_close($ch); // 打印结果方便排查 echo '<div style="color:red;margin:10px 0;">' . $result . '</div>'; } ?> <!DOCTYPE html> <head> <title>Form submission</title> </head> <body> <form action="" method="post"> First Name: <input type="text" name="first_name" required><br> Last Name: <input type="text" name="last_name" required><br> Email: <input type="email" name="email" required><br> Message:<br><textarea rows="5" name="message" cols="30"></textarea><br> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
三、如果修复后仍无法收到邮件,按以下步骤排查
- 核对Auth Token权限:确认你使用的Token有发送邮件的权限,且没有拼写错误。
- 核对事件ID:确认
personalized-welcome-email和你在Courier后台创建的模板事件ID完全一致。 - 查看Courier后台日志:登录Courier平台查看消息发送日志,能明确看到请求是否成功、失败原因是模板参数缺失还是渠道配置错误。
- 检查收件箱的垃圾邮件文件夹:部分邮件服务商可能会把自动发送的邮件归类到垃圾邮件。
- 确认Courier渠道配置:检查你在Courier后台绑定的邮件发送服务商配置正常,没有额度限制或者配置错误。
内容的提问来源于stack exchange,提问作者Ryland Webb
相关产品推荐
相关产品推荐

