You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP调用Mailtrap API发邮件时to字段类型错误求助

解决Mailtrap API发送邮件时to字段类型错误的问题

错误信息明确提示:invalid type for field \to`, expected: `array`, given: `object`,原因是你传递的to`字段是单个对象(关联数组序列化后转为JSON对象),但Mailtrap API要求该字段必须是包含收件人对象的数组,哪怕只有一个收件人也需要用数组包裹。

修改后的代码

// 单个收件人也要放到数组中
$to = [["email" => $email]];
$postData = [
    "to" => $to,
    "from"=> "no-reply@k.com",
    "name"=>" Please Verify Email Address!",
    "subject" => " Verify Email and Complete Registration",
    "sender_id" => "ym",
    "callback_url" => "ym.com",
    "text" => $msg,
    "category"=> $type."Email Verification - Onboarding"
];
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($postData),
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer 99',
        'Content-Type: application/json'
    ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

关键修改点

  • 将原来的$to = ["email"=>$email];改为$to = [["email" => $email]];,把单个收件人对象包裹进数组,满足API对to字段的类型要求。

内容的提问来源于stack exchange,提问作者Ahmed Yasser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:15:37