php - SendGrid 在 Wordpress 函数中使用 api v3 和 PHP 库发送给多个收件人
问题描述
我正在使用带有 php 库的 SendGrid v3 api 来尝试将其作为 WordPress 功能的一部分发送给多个收件人。我可以使用 SendGrid 示例代码成功发送电子邮件并对多个收件人进行硬编码。但是,当我查询数据库以尝试构建 to: 电子邮件地址列表时,它总是失败并出现 400 错误。这是我正在使用的 SendGrid 代码。它适用于实时数据和硬编码。但是,我似乎无法从我的数据库查询中正确构建 $tos 数组。我已经阅读了文档和我能找到的每个教程。我还联系了 Sendgrid 支持。
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Example User");
$tos = [
"test+test1@example.com" => "Example User1",
"test+test2@example.com" => "Example User2",
"test+test3@example.com" => "Example User3"
];
$email->addTos($tos);
$email->setSubject("Sending with SendGrid is Fun");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
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";
}
这是我的 WordPress 查询: $sends = $wpdb->get_results( "SELECT * FROM test
" );
如何正确编码数据库查询中的 $tos 变量,以便 $email->addTos($tos) 不会出错?
谢谢。
解决方案
根据此页面,该addTos
功能已失效,SendGrid 的 API 不再支持该功能:“该addTos()
方法已移至addTo()
当前不支持传入的数组”。
所以:
使用您的test
数据库:
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Example User");
$userResults = $wpdb->get_results( "SELECT `email` FROM `test`", ARRAY_A ); //Select as Associative Array
foreach($userResults as $userKey => $userValue){
$userEmail = $userValue['email']);
if ( is_email( $userEmail ) ) { //Validate properly formatted email structure
$email->addTo($userValue['email']); // If you hade a name column you could use: $email->addTo($userValue['email'], $userValue['name']);
}
}
$email->setSubject("Sending with SendGrid is Fun");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
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";
}
使用wp_users
数据库:
$userResults = $wpdb->get_results( "SELECT `user_email`, `user_nicename` FROM `wp_users`", ARRAY_A );
foreach($userResults as $userKey => $userValue){
$email->addTo($userValue['user_email'], $userValue['user_nicename']);
}
推荐阅读
- mongodb - MongoDB 自动更新文档以匹配模式
- c# - LDAP 查询未返回所有查询的属性
- google-api-python-client - 在 dialogflow cx 中将声音更改为女性
- algorithm - 连续图像上的生长区域算法
- python - 如何设置 x 轴的特定范围并增加绘图的长度?
- c# - 在 C# windows 窗体中的树视图中面临问题,详细信息如下:
- ios - iphone模拟器缺少构建产品反应原生
- autodesk-forge - 如何在 Autodesk Forge Viewer 中获取和恢复当前设置
- ionic5 - 如何在 ionic 5 的 ion-avatar 下显示文本?
- firebase - FirebaseFunctions 缺少数据字段?