首页 > 解决方案 > 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) 不会出错?

谢谢。

标签: phpwordpresssendgrid-api-v3

解决方案


根据此页面,该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']);
}

推荐阅读