PHP中使用SendGrid API传递数组变量发送邮件报错求助
问题
我有一个邮箱地址数组,想用PHP的SendGrid API遍历数组给每个邮箱发送邮件,但SendGrid无法正常识别变量。我尝试的代码如下:
$no_contacts = count($contacts); for ($i=0; $i<$no_contacts; $i+=1){ $contact = $contacts[$i]; $email = new \SendGrid\mail\Mail(); $email->setFrom("examplesender@mail.com", "App Name"); $email->setSubject("Update"); $email->addTo($contact, "Name"); $email->addContent( "text/html", $messages[0] ); $sendgrid = new \SendGrid('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'); try { $response = $sendgrid->send($email); //print $response->statusCode() . "\n"; //print_r($response->headers()); //print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage() ."\n"; } }
传递$messages[0]可以正常运行,但在addTo方法中传递$contacts[$i]或$contact时无法生效。我尝试让$contacts[$i]存储带引号的"examplesreciever@mail.com"或不带引号的examplereciever@mail.com,两种情况均返回错误:
Fatal error: Uncaught SendGrid\Mail\TypeException: "$emailAddress" must be a valid email address. Got: examplereciever@mail.com
解决方案
校验邮箱格式并清理无效字符:
循环内先对邮箱地址做格式验证,同时去除字符串前后的空白字符(很多时候问题源于隐藏的空格、换行符),代码如下:$contact = trim($contacts[$i]); if (!filter_var($contact, FILTER_VALIDATE_EMAIL)) { echo "无效邮箱:$contact,跳过\n"; continue; }检查数组的真实数据内容:
用var_dump($contacts);打印数组,确认每个元素是否为纯邮箱字符串,有没有多余的引号、转义符或HTML实体。如果是从数据库或表单获取的数据,存在转义的情况,可使用stripslashes($contact)去除转义字符。优化SendGrid实例化逻辑:
不要在循环内重复创建\SendGrid实例,将其移到循环外部,减少资源消耗:$sendgrid = new \SendGrid('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'); $no_contacts = count($contacts); for ($i=0; $i<$no_contacts; $i+=1){ // 循环内的邮件构建逻辑 }改用批量发送提升效率:
单条遍历发送效率较低,SendGrid支持一次性添加多个收件人,代码示例:$email = new \SendGrid\mail\Mail(); $email->setFrom("examplesender@mail.com", "App Name"); $email->setSubject("Update"); $email->addContent("text/html", $messages[0]); foreach ($contacts as $contact) { $cleanContact = trim($contact); if (filter_var($cleanContact, FILTER_VALIDATE_EMAIL)) { $email->addTo($cleanContact, "Name"); } } $sendgrid = new \SendGrid('你的API密钥'); try { $response = $sendgrid->send($email); } catch (Exception $e) { echo '捕获异常: '. $e->getMessage() ."\n"; }
内容的提问来源于stack exchange,提问作者littlelegs

