使用PHP SDK通过SendGrid和PHP发送电子邮件

时间:2019-09-03 23:45:29

标签: php sendgrid

经过几个小时的研究,我正在寻求帮助。

我想使用https://github.com/sendgrid/sendgrid-php处的PHP SDK使用SendGrid API通过PHP发送电子邮件。

实际上,我的代码如下:

require(“ sendgrid / sendgrid-php.php”);

$email = new \SendGrid\Mail\Mail(); 
$email->setFrom("info@test.org", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("send@gmail.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('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";

我在必需的.env文件中也有API密钥。我只是将其命名为.env。我不知道这是否正确。

此文件的内容如下:

export SENDGRID_API_KEY='SG.xxxxxxxxxxxx'

测试页面时,出现以下错误:

401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: nginx [2] => Date: Tue, 03 Sep 2019 23:44:21 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}]}

请问我在做什么错?

我冲了文档,但是找不到导致错误的原因。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

.env需要vlucas/phpdotenv通过composer安装

composer require vlucas/phpdotenv

并具有不带export关键字或引号的API密钥

SENDGRID_API_KEY=SG.xxxxxxxxxxxx
相关问题