【问题标题】:Send an email with SendGrid and PHP using the PHP SDK使用 PHP SDK 通过 SendGrid 和 PHP 发送电子邮件
【发布时间】:2019-09-03 23:45:29
【问题描述】:

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

我想使用 SendGrid API 使用 PHP SDK 发送我的电子邮件与 PHP 在这里找到 https://github.com/sendgrid/sendgrid-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}]}

请问我做错了什么?

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

非常感谢您的帮助。

【问题讨论】:

  • 你使用的是纯php还是Laravel这样的框架?您是否使用 composer 安装了 vulcas/dotenvsendgrid-php 包?
  • 您好,我使用的是纯 PHP。而且我不使用 Composer 安装 Vulcan/dotenv 或软件包。

标签: php sendgrid


【解决方案1】:

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

composer require vlucas/phpdotenv

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

SENDGRID_API_KEY=SG.xxxxxxxxxxxx

【讨论】:

  • 如果我不使用 Composer,有没有像文档中解释这样的选项?
  • 那么就不要使用getenv 函数并硬编码您的 API 密钥
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
相关资源
最近更新 更多