首页 > 解决方案 > 尝试发送电子邮件时不允许使用 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。

任何帮助表示赞赏。谢谢。

标签: phphtmlemailsendgrid

解决方案


这不是解决方案,而是调试帮助:

代替:

$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);

}

然后在这里发布结果。


推荐阅读