Good afternoon, everyone! I am getting a CORS error when attempting to test Sendgrid in PHP. Here is my setup:
I have a Vue based from end which calls a vanilla PHP api for some basic tasks. Both the front end and API sit on an Amazon Lightsail server. In one of those PHP files I put the sendgrid test. NOTE: This api is truly vanilla, and I setup the sendgrid files manually since there is no composer file. Here is the error I get when the send grid functionality is called:
Array
(
[0] => HTTP/1.1 202 Accepted
[1] => Server: nginx
[2] => Date: Fri, 04 Dec 2020 16:51:19 GMT
[3] => Content-Length: 0
[4] => Connection: keep-alive
[5] => X-Message-Id: X8jfBPyWS8eU0jhW5qWJrQ
[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] =>
)
Yes, I read the cors link provided, but I don't think it applies to my situation. Here is the relevant PHP:
ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_STRICT);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header("Content-type: application/json; charset=utf-8");
include_once '../lib/sendgrid-php/sendgrid-php.php';
After this comes other code that doesn't factor into the SendGrid aspect, so I won't clutter the page by posting it. Below is where the sendgrid part of the file executes:
$apiKey = "myapikey";
$email = new \SendGrid\Mail\Mail();
$email->setFrom("REALEMAIL", "Alert");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("TESTRECEIPTEMAIL", "MY NAME");
$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($apiKey);
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";
}
To address obvious points first: TESTRECEIPTEMAIL and REALEMAIL are valid emails in the actual code and the API key referenced IS a valid api key. And no, I do not plan on leaving the API key just sitting in the file, like I said, all I'm trying to do at the moment is to get sendgrid to work first.
Any insight into this would be greatly appreciated. Thanks in advance!