PHP集成SendGrid时SendAt邮件调度功能异常,求排查建议
SendGrid PHP集成中SendAt邮件调度功能失效问题排查与解决
问题描述
我正在将SendGrid集成到PHP应用中,发送脚本可正常运行,但邮件调度(SendAt)功能无法生效。我是SendGrid新手,已附上相关代码,打印SendAt对象显示其已正确构造(值为1666639700),现询问是否正确集成了SendAt功能,以及如何使其正常工作。
相关代码
require '../sendgrid/vendor/autoload.php'; // If you're using Composer (recommended) use SendGrid\Mail\From; use SendGrid\Mail\HtmlContent; use SendGrid\Mail\Mail; use SendGrid\Mail\PlainTextContent; use SendGrid\Mail\To; use SendGrid\Mail\SendAt; $from = new From("hello@tigerrocklincoln.com", "Tiger-Rock"); $tos= [new To( "$email", "$first $last", [ '{{First_Name}}' => $first, '{{Last_Name}}' => $last, '{{X_Days}}' => $days, ], "We Miss You" )]; $globalSubstitutions = [ '-time-' => "2018-05-03 23:10:29" ]; $plainTextContent = new PlainTextContent("$phrase"); $htmlContent = new HtmlContent("$phrase"); $sendat=new SendAt(1666639700); print_r($sendat); $email = new Mail( $from, $tos, $subject, // or array of subjects, these take precedence $plainTextContent, $htmlContent, $globalSubstitutions, $sendat ); $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"; }
注:$tos中的$email、$first等变量会替换为实际信息,打印SendAt对象结果为:SendGrid\Mail\SendAt Object ( [send_at:SendGrid\Mail\SendAt:private] => 1666639700 )
解决方案
核心问题
你当前的错误在于直接将SendAt对象传入Mail类的构造函数——SendGrid PHP库的Mail构造函数并不支持这个参数,所以你的调度设置被直接忽略了,这就是功能失效的原因。
正确实现步骤
修改代码中创建Mail对象并设置调度时间的部分:
- 先创建
Mail对象,移除构造函数中的$sendat参数:
$email = new Mail( $from, $tos, $subject, $plainTextContent, $htmlContent, $globalSubstitutions );
- 通过
setSendAt()方法设置调度时间,有两种方式:- 方式一:使用已创建的
SendAt对象的时间戳
$email->setSendAt($sendat->getSendAt());- 方式二:直接传入时间戳(更简洁)
$email->setSendAt(1666639700); - 方式一:使用已创建的
额外检查项
- 确认你的SendGrid账户已启用邮件调度功能(默认启用,若之前禁用需在控制台开启)。
- 调度时间必须是未来时间,且不能超过当前时间72小时(SendGrid的硬性限制)。
- 检查你的API密钥是否拥有
mail.send权限(这是发送邮件的基础权限)。
内容的提问来源于stack exchange,提问作者user2089016
相关产品推荐
相关产品推荐

