Reputation: 2031
I am sending email using sendgrid PHP. Here is my code:
require("sendgrid-php.php");
$from = new SendGrid\Email("Example User", "[email protected]");
$subject = "Sending with SendGrid is Fun";
$to = new SendGrid\Email("Example User", "[email protected]");
$content = new SendGrid\Content("text/plain", "and easy to do anywhere, even with PHP");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = getenv('SG.key......');
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo '<pre>';
print_r($response->headers());
echo '</pre>';
echo $response->body();
When I run above code it's showing me following error message:
401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: nginx [2] => Date: Mon, 29 May 2017 17:52:44 GMT [3] => Content-Type: application/json [4] => Content-Length: 88 [5] => Connection: keep-alive [6] => X-Frame-Options: DENY [7] => Access-Control-Allow-Origin: https://sendgrid.api-docs.io [8] => Access-Control-Allow-Methods: POST [9] => Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl [10] => Access-Control-Max-Age: 600 [11] => X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html [12] => [13] => ) {"errors":[{"message":"Permission denied, wrong credentials","field":null,"help":null}]}
I don't understand why I getting permission related error because I have just created the API key.
Upvotes: 2
Views: 5455
Reputation: 1
I had the same problem.
All you have to do is deleting the getenv
function like this:
$apiKey = 'SG.key......';
$sg = new \SendGrid($apiKey);
Another way could be:
$sendgrid = new \SendGrid('SG..Tw');
Remember that the API key and the from address you set in your code should be related to the email sender stablished for it, not the email that you used when signing up.
Upvotes: 0
Reputation: 1165
That is very common. It will take hardly an hour to understand and do. You need to set env or use username-password authentication system. Please read the official document on Github, documentation here and documentation here.
Upvotes: 2