Sendgrid V3 电子邮件 API PHP 集成

问题描述

您好 Sendgrid 正在更改电子邮件传送 API 设置,我已经在许多网站上使用以下代码很长时间了,现在我无法使用它们。

我一直在使用带有以下代码的 V2:

<?PHP

$url = 'https://api.sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';

$json_string = array(

  'to' => array(
    'hello@gmail.com','hello@gmail.com'
  ),'category' => 'test_category'
);


$params = array(
    'api_user'  => $user,'api_key'   => $pass,'x-smtpapi' => json_encode($json_string),'to'        => 'hello@gmail.com','subject'   => 'testing from curl','html'      => 'testing body','text'      => 'testing body','from'      => 'example@sendgrid.com',);


$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session,CURLOPT_POST,true);
// Tell curl that this is the body of the POST
curl_setopt ($session,CURLOPT_POSTFIELDS,$params);
// Tell curl not to return headers,but do return the response
curl_setopt($session,CURLOPT_HEADER,false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session,CURLOPT_SSLVERSION,CURL_SSLVERSION_TLSv1_2);
curl_setopt($session,CURLOPT_RETURNTRANSFER,true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
print_r($response);

现在,我必须切换到他们的 V3 API。超过 2 天我无法弄清楚。

我读过一些地方,如果我只是用 API 密钥替换我的密码,它应该可以工作,但我尝试过,但我没有穿。

我也试过下面的代码

<?PHP
// Uncomment next line if you're not using a dependency loader (such as Composer)
require_once 'sendgrid/sendgrid-PHP.PHP';

$email = new \SendGrid\Mail\Mail(); 
$email->setFrom("test@example.com","Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("test@example.com","Example User");
$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('MY_API_KEY_HERE_XXXXXXXXXXXXXXXX_XXXX'));
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";
}

我两次都遇到的错误是:

 401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: Nginx [2] => Date: Sun,03 Jan 2021 19:50:56 GMT [3] => Content-Type: application/json [4] => Content-Length: 88 [5] => Connection: keep-alive [6] => Access-Control-Allow-Origin: 
https://sendgrid.api-docs.io [7] => Access-Control-Allow-Methods: POST [8] => Access-Control-Allow-Headers: Authorization,Content-Type,On-behalf-of,x-sg-elas-acl [9] => Access-Control-Max-Age: 600 [10] => X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html [11] => [12] => ) {"errors":[{"message":"Permission denied,wrong credentials","field":null,"help":null}]}

如果你能指导我哪里做错了,那会很有帮助,我自过去 3 天以来一直被困在这里。绕来绕去。 谢谢 新年快乐!

解决方法

你有进步吗?我也有问题。 我已将用户名更改为“apikey”并将密码更改为我生成的 api 密钥,但出现“错误的用户名/密码”错误。我有一个支持票。文档冲突。