php - 尝试发送电子邮件时不允许使用 SendGrid API 405 方法
问题描述
编辑 3:这个 405 错误与我的 IIS Express 开发环境有关。我设法让我的 azure web 应用程序上的一切正常工作。
编辑2:呃。我没有设置环境变量。
编辑:感谢您的帮助,我取得了一些进展。即使我使用的是 SendGrid 的新 API 密钥,我现在似乎也遇到了身份验证问题。我目前收到此错误:
401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: nginx [2] => Date: Sun, 17 Nov 2019 20:50:16 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 文件,并且正在为我的网站获取 SendGrid。
<form method="post" action="php/send_form_email.php">
<input type="submit" value="click on me!">
</form>
然后这里是 send_form_email.php 文件:
<?php
// You need to install the sendgrid client library so run:
// composer require sendgrid/sendgrid
try
{
require 'D:/home/site/wwwroot/vendor/autoload.php';
}
catch (Exception $e) {
echo 'exception' . '<br>';
var_dump($e);
}
$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('API_KEY_HERE'));
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";
}
?>
我在我的机器和我的 azure web 应用程序上都安装了我成功遇到的任何 composer/sendgrid/curl。
任何帮助表示赞赏。谢谢。
解决方案
这不是解决方案,而是调试帮助:
代替:
$response = $sg->client->mail()->send()->post($mail);
if ($response->statusCode() == 202) {
// Successfully sent
echo 'done';
} else {
echo 'false';
}
经过
try {
$response = $sg->client->mail()->send()->post($mail);
if ($response->statusCode() == 202) {
echo 'done';
} else {
echo 'false' . '<br>';
var_dump($response);
}
} catch (Exception $e) {
echo 'exception' . '<br>';
var_dump($e);
}
然后在这里发布结果。
推荐阅读
- html - 在悬停时使背景变暗
- c# - 指定的可执行文件不是此 OS 平台的有效应用程序。
- ansible - 如何使用 ansible 下载和提取 apache tomcat 并重命名 unzaip 文件
- javascript - Javascript变量在onload函数内没有改变
- python - pycharm 中的警告,带有 sort(key = len) 函数
- postgresql - 如何解决空 docker-entrypoint-initdb.d 的问题?(PostgreSQL + Docker)
- python - Python:通过将对象分配给另一个对象来修改它
- javascript - 让 ng-view 只显示它的内容,而不是它本身
- docker - 如何在 Docker 上设置 Apache Spark 和 Zeppelin
- c++ - C++17/20 并行算法:对对象的非同步访问