0

Im trying to send an email with php using sendgrid and I'm not able to do it

I'm using this code

<?php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
// Comment out the above line if not using Composer
// require("<PATH TO>/sendgrid-php.php");
// If not using Composer, uncomment the above line and
// download sendgrid-php.zip from the latest release here,
// replacing <PATH TO> with the path to the sendgrid-php.php file,
// which is included in the download:
// https://github.com/sendgrid/sendgrid-php/releases

$email = new \SendGrid\Mail\Mail(); 
$email->setFrom("test1@example.com", "test1");
$email->setSubject("Subject example");
$email->addTo("test@example.com", "Example");
$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";
}

and I'm getting this error

401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: nginx [2] => Date: Tue, 30 Oct 2018 08:11:54 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}]}

I was using this tutorial, quickstart, idk what to do, thanks in advance. https://github.com/sendgrid/sendgrid-php

1 Answers1

0

I'm on the Twilio blog PHP team.

Based on the error message provided, I'm guessing that you've either not set the SENDGRID_API_KEY environment variable or that it's not set to your current, active, SendGrid API key. Please double-check that it's both set and correct. After that, if the issue persists, let me know and I'll see what else I can do.

Matthew Setter
  • 2,397
  • 1
  • 19
  • 18