I'm getting an error when trying to use the Sendgrid API. The error comes up as:
Fatal error: Uncaught Error: Class 'Sendgrid' not found in signin.php:xxx Stack trace: #0 index.php(yy): require() #1 {main} thrown in signin.php on line xxx.
I installed Sendgrid using composer. I then register the autoloader like:
index.php
require __DIR__.'/../vendor/autoload.php';
Then follow the guide like on the link below.
signin.php
use SendGrid\Mail\From;
use SendGrid\Mail\To;
use SendGrid\Mail\Mail;
$from = new From("test@example.com", "Example User");
$to = [
new To(
"test+test1@example.com",
"Example User",
[
'subject' => 'Subject'
]
)
];
$email = new Mail(
$from,
$tos
);
$email->setTemplateId("REDACTED");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
The autoload.php file works with other composer classes.
Steps I've tried so far:
Reference
https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md#send-an-email-to-a-single-recipient
composer.json
{
"require": {
"sendgrid/sendgrid": "^8.0",
}
}
I ended up putting the code inside of a function and it worked without issue. I required mailer.php right after autoload.php.
In case someone runs into this issue, here is what I did. Obviously, you'll want to customize it to your needs.
mailer.php
<?php
declare(strict_types=1);
use SendGrid\Mail\From;
use SendGrid\Mail\To;
use SendGrid\Mail\Mail;
function mailer() {
$from = new From("test@example.com", "Example User");
$to = new To(
"test+test1@example.com",
"Example User",
[
'subject' => 'Subject'
]
);
$email = new Mail($from, $to);
$email->setTemplateId("REDACTED");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
}
I'm not sure why my original code did not work, but this solution works so I'll leave it at that.