Sendgrid-php: Getting "Fatal error: Class 'SendGrid\Email' not found"

Created on 28 Dec 2016  路  38Comments  路  Source: sendgrid/sendgrid-php

I've tried this fix below, but it didn't work: http://stackoverflow.com/questions/29000442/sendgrid-gives-fatal-error

question

Most helpful comment

@thinkingserious @hectorsabina I can confirm that even within WordPress 4.5.x this issue could happen due to a missing \ at beginning, cause the runtime thinks that the namespace is the current one (your plugin's namespace) hence the following code will work if

1) You put in the root folder of your WP plugin the provided sendgrid-php unzipped contents within a sendgrid-php folder;
2) Add a require_once dirname(__FILE__) . "/sendgrid-php/sendgrid-php.php";

private function sendEmail() {

        $from = new \SendGrid\Email(null, "[email protected]");
        $subject = "Weekly Customers Update";
        $to = new \SendGrid\Email(null "[email protected]");

        $content = new \SendGrid\Content("text/plain", "Report attached.");
        // $content = new \SendGrid\Content("text/html", "<h1>Sending with SendGrid is Fun and easy to do anywhere, even with PHP</h1>");

        $mail = new \SendGrid\Mail($from, $subject, $to, $content);
        $to = new  \SendGrid\Email(null, "[email protected]");
        $mail->personalization[0]->addTo($to);

        $apiKey = 'xxxxx';
        $sg = new \SendGrid($apiKey);
        $response = $sg->client->mail()->send()->post($mail);
        //echo $response->statusCode();
        //echo $response->body();
        //print_r($response->headers());
    }

Hope this helps, saved my time!!!

All 38 comments

I have the same issue... and adding the require 'lib/SendGrid/Email.php'; does not work and throws the error for re-declaring a class.

Yep, same thing here.

If you are using Composer: Can you please check that your vendor/autoload.php file exists?

If you are not using Composer, simply download and install the latest packaged release of the library as a zip.

Then require the library from package:

require("path/to/sendgrid-php/sendgrid-php.php");

From @jeanCarlosRacoski on the other thread:

  • Composer is not being used;
  • That ship has sailed a long time ago my friend, we have read the tutorial thanks, but we need a little more info from the experts

Either there is another lib to download besides the two found and reported here, which may content all the required files... or something is very wrong with that integration tutorial. That is my guess after all these days trying and even editing their files and folders.

Sorry to ask this, but just to check, you replaced "/path/to" with the absolute path to your sendgrid-php directory, right?

If not, go in your command line terminal to the sendgrid-php directory and type "pwd" you should get a path, replace /path/to with that path.

If you did and it still isn't working, it is worth trying to navigate to your sendgrid-php directory and verifying that the sendgrid-php.php file has executable permissions and that it is actually in your directory.

I have opened the zip file linked from the tutorial and the sendgrid-php.php is in fact there. Again, if you can check permissions on the files in the directory as that may be the issue, since the files (sendgrid-php.php and vendor/autoload.php) are both included in the downloadable zip directory.

This is what the permissions look like in my download, which is not going to work on a server:
https://www.evernote.com/l/AaHI632hePpH67zKd4NbL5kKU8_GpgIJZ18 you need at least executable permissions. This is likely your computer attempting to keep the files "safe" until you purposefully change the permissions.

I did changed the path, or else the error would be different, agreed? Cause I had this issue with the file not found and the errors are not the same.

The class is missing, not the file.

these are the file permissions
-rw-rw-r-- 1 ubuntu ubuntu 39 Nov 17 23:08 sendgrid-php.php

I cannot speak to everyone's server settings, but I believe that you need executable permissions. This post on Stackoverflow is saying that depending on your settings you might be able to have 644, but I always ran 755 when I was building software. :)

http://stackoverflow.com/a/2096288/1296778

ok, changed the permissions:
-rwxr-xr-x 1 ubuntu ubuntu 39 Nov 17 23:08 sendgrid-php.php
(755 just like you said)
Sadly, still the same error.

Im also having this issue.

I included the library (and the path is definitely correct) but as soon as I create a 'new SendGrid\Email', I get the 'fatal error, class not found' message.

Im not using Composer and the require sendgrid-php.php suggestion doesnt help as this file doesnt exist in the current version of the library.

@mbernier I changed permissions to 0755, just like @JeanCarlosRacoski did and I'm still getting the error as well.

I'm not sure it has to do with permissions, since I am running SendGrind on v2 (on a different process page) using the v2 library (without Composer) as well, and the file perm there is 0644.

fwiw: Usually, when installing the library, all of the directory perms are set to 0755; individual file perms are 0644.

@paoga87,

What version of this library are you using?
How did you install it?
What version of PHP are you running on your server?
Could you provide the sample code that is not working?

Thanks!

@Laver2k,

Have you tried downloading from here? https://github.com/sendgrid/sendgrid-php#alternative-install-package-from-zip

@JeanCarlosRacoski,

What version of this library are you using?
How did you install it?
What version of PHP are you running on your server?
Could you provide the sample code that is not working?

Thanks!

@ramonbez,

What version of this library are you using?
How did you install it?
What version of PHP are you running on your server?
Could you provide the sample code that is not working?

Thanks!

To be sure, I've downloaded the files again from the link you have suggested, but the error remains.
I have not installed it, I've created the key variable and required the files after uploading them (and yes the path is correct btw)

PHP Version 5.5.9-1ubuntu4.20

I am currently using the tutorial code, however I have changed the path to the lib (which again, is correct) and email addresses of course.

(https://app.sendgrid.com/guide/integrate/langs/php)

// If you are not using Composer
require("path/to/sendgrid-php/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('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->headers();
echo $response->body();

Hello @JeanCarlosRacoski,

Thanks for the additional details

I was not able to reproduce. Here is what I did:

wget https://sendgrid-open-source.s3.amazonaws.com/sendgrid-php/sendgrid-php.zip
unzip sendgrid-php.zip
cd sendgrid-php
code test.php
<?php
require("./sendgrid-php.php");
$from = new SendGrid\Email("DX PHP Test", "[email protected]");
$subject = "Sending with SendGrid is Fun";
$to = new SendGrid\Email("Elmer", "[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('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
php ./test.php

The result was a sent email with a return code of 202

@thinkingserious:

What version of this library are you using?
The latest version, found at the URL you provided (https://sendgrid-open-source.s3.amazonaws.com/sendgrid-php/sendgrid-php.zip)

How did you install it?
Unzipped folder, put the unzipped files within my code repo.

What version of PHP are you running on your server?
5.4.28

Could you provide the sample code that is not working?

<?php
    require ("./sendgrid-php.php");

    $from = new SendGrid\Email("DX PHP Test", "[email protected]");
    $subject = "Sending with SendGrid is Fun";
    $to = new SendGrid\Email("Paola", "[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.my_key_here');
    $sg = new \SendGrid($apiKey);
    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
?>

--Require path working correctly.

Note: I am now getting a 401 response code. I have tested my API key via cURL (JSON) and I am able get emails that way; but this code keeps returning 401 status code.

Hello @paoga87,

That error is related to your API key.

Note that $apiKey = getenv('SG.my_key_here'); will not work.

Instead, try $apiKey = 'SG.my_key_here';

For details:
https://github.com/sendgrid/sendgrid-php/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key

@thinkingserious awesome! Got it working now; 202 response and did receive the email.
Thanks a lot for your help!

@thinkingserious
Quick question: Using the Mail Helper Library, how can we add custom arguments and/or attachments? I tried following the example here (https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L31) but it's not working.

Here's a snapshot of what I have:

<?php
    require ("./sendgrid-php.php");

    $from = new SendGrid\Email("DX PHP Test", "[email protected]");
    $subject = "Sending with SendGrid is Fun";
    $to = new SendGrid\Email("Paola", "[email protected]");
    $content = new SendGrid\Content("text/plain", "and easy to do anywhere, even with PHP");

        $personalization = new SendGrid\Personalization();
        $personalization->addCustomArg("meeting_name","myMeetingNameHere");
        $attachment = new SendGrid\Attachment();
    $attachment->setType("application/pdf");
    $attachment->setFilename("myFile.pdf");

    $mail = new SendGrid\Mail($from, $subject, $to, $content);
        $mail->addPersonalization($personalization);
        $mail->addAttachment($attachment);

    $apiKey = 'SG.my_key_here';
    $sg = new \SendGrid($apiKey);
    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
?>

400 Response code.

Hello @paoga87,

It looks like you are missing the base64 encoded content.

Please take a look at the link above.

Thanks!

@thinkingserious
I added the following:

     $myPDF = 'path/to/myFile.pdf';
     $myPDF_encoded = chunk_split(base64_encode(file_get_contents($myPDF)));

     $attachment = new SendGrid\Attachment();
     $attachment->setContent($myPDF_encoded);

Still returning response 400.

Thank you for looking at this!

Hi @paoga87,

I think you need to remove the chunk_split. Please see: https://github.com/sendgrid/sendgrid-php/issues/272

@thinkingserious yes, that did it.
Thank you for your help!

I might be a bit late to the party, but for those still having issues using this lib without composer, try naming classes this way:

$from = new \SendGrid\Email("Example User", "[email protected]");

Notice the extra \ at the beginning. This is to import this class from the global namespace, instead from the one you've defined already for the class you're using this library from (check php namespaces for more info).

Thanks for the feedback @hectorsabina!

I think your example would be great to put here. Would you mind submitting a PR?

Thanks again!

With Best Regards,

Elmer

I found that this happen because sendgrid use extra library that loaded by composer

vendor\sendgrid\php-http-client\

and of course you cannot get these without composer .

basically need two files from it

Client.php
Response.php

@alyak46141414,

If you are not using Composer, you can download the relevant files here.

Thanks!

@thinkingserious @hectorsabina I can confirm that even within WordPress 4.5.x this issue could happen due to a missing \ at beginning, cause the runtime thinks that the namespace is the current one (your plugin's namespace) hence the following code will work if

1) You put in the root folder of your WP plugin the provided sendgrid-php unzipped contents within a sendgrid-php folder;
2) Add a require_once dirname(__FILE__) . "/sendgrid-php/sendgrid-php.php";

private function sendEmail() {

        $from = new \SendGrid\Email(null, "[email protected]");
        $subject = "Weekly Customers Update";
        $to = new \SendGrid\Email(null "[email protected]");

        $content = new \SendGrid\Content("text/plain", "Report attached.");
        // $content = new \SendGrid\Content("text/html", "<h1>Sending with SendGrid is Fun and easy to do anywhere, even with PHP</h1>");

        $mail = new \SendGrid\Mail($from, $subject, $to, $content);
        $to = new  \SendGrid\Email(null, "[email protected]");
        $mail->personalization[0]->addTo($to);

        $apiKey = 'xxxxx';
        $sg = new \SendGrid($apiKey);
        $response = $sg->client->mail()->send()->post($mail);
        //echo $response->statusCode();
        //echo $response->body();
        //print_r($response->headers());
    }

Hope this helps, saved my time!!!

I am testing my locally. Is that the problem that I have? Do I need to take it to a live server?

Hello @preshboy,

What error are you seeing? How did you install the SDK and what version are you using?

Thanks!

With Best Regards,

Elmer

i am trying to run the code on windows 10 using xampp but still getting the error. please help me.This is the code i am trying to run. i saved this file in folder named sendgrid which also contains the unzipped files of the sendgrid repository.

require './vendor/autoload.php';
include_once('./credentials.php');//including the api key in this file
require("C:/xampp/htdocs/sendgrid/sendgrid-php.php");
$FROM_EMAIL = '[email protected]';

$TO_EMAIL = '[email protected]';

$subject = "Test from youtube";
$from = new SendGrid\Email(null, $FROM_EMAIL);
$to = new SendGrid\Email(null, $TO_EMAIL);
$htmlContent = 'aaa';

$content = new SendGrid\Content("text/html",$htmlContent);

$mail = new SendGrid\Mail($from, $subject, $to, $content);

$sg = new \SendGrid($API_KEY);
$response = $sg->client->mail()->send()->post($mail);

if ($response->statusCode() == 202) {
    echo 'done';
} else {
    echo 'false';
    print_r($response);
}

?>

if you're like me and hate composer (don't even get me started) THE GOOD NEWS IS you _can_ get this to work so- just so you know .. almost everything "they" (SendGrid) direct you to online is either cripplingly wrong (wild goose chase), out of date (with nothing to alert you), or missing essential components (won't work out of the box) .... for example here we see "they" (SendGrid) simply took out \SendGrid\Email() and replaced it with \SendGrid\Mail\Mail() and so the callers are slightly different .. i.e.

        $sendgrid = new SendGrid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom("[email protected]", "Example User");
    $email->setSubject("Sending with SendGrid is Fun");
    $email->addTo("[email protected]", "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>"
    );

    //optional to attach a file<START>
    $att1 = new \SendGrid\Mail\Attachment();
    $att1->setContent( file_get_contents("/path/to/some/test_attach.txt") );
    $att1->setType("text/plain");
    $att1->setFilename("test_attach.txt");
    $att1->setDisposition("attachment");
    $email->addAttachment( $att1 );
    //optional to attach a file</END>       

    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 use v3 YOU WILL NEED PHP 5.6. (rightly or wrongly PHP 5.4 is the ceiling of redhat/centos at time of writing) and YOU CANNOT USE postfix anymore (despite them never specifically saying this nor labeling their postfix examples v2 max, i.e. disabled as of 17th April 2019) SO -> you have to use v3 -> you have to upgrade to 5.6 ... i.e. you are stuck with the client or the curl at v3 (they don't simply say this) also re: the Curl mechanism (while it does work with 5.4) carries a) no documentation on using attachments AND b) utilizes illegal json_encoding PHP cannot output ( PHP cannot give "{[{}]}" it's always "{"0":[{}]}")

but regardless not only MUST you use the SendGrid PHP client at 5.6 PHP (again no, server postfix option) _you still need to know you need TWO projects:_ "php-http-client-master" and "sendgrid-php-master" (BOTH repos) and this is undocumented: then you need to do the following: and the /lib/loader.php in "sendgrid-php-master" needs these two lines adding at the end

               require_once '/your/path/to/php-http-client-master/lib/Client.php';
               require_once '/your/path/to/php-http-client-master/lib/Response.php';

you also need to add this (sadly more sloppiness from SendGrid)

             require_once __DIR__ . '/mail/TypeException.php';

Incidentally I also edited sendgrid-php-master\sendgrid-php.php to this
< ? php
require __DIR__ . '/lib/loader.php';
? >

theoretically adding composer would mean you could probably avoid all this but for some servers this is out of the question (implementing composer on a different branch of my PHP project took 3 weeks - I am not repeating this) since composer introduces a breaking change in the way PHP handles includes and class autoloading

Hi, I'm also trying to use it without composer. I downloaded the last version of sendgrid-php, I copied it into my folder, I put the require:

require("sendgrid-php/sendgrid-php.php");

I edited the send mail file with my API Key...

And I get this:

401 Array ( [0] => HTTP/1.1 401 Unauthorized [1] => Server: nginx [2] => Date: Mon, 29 Apr 2019 14:08:49 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}]}

Hello @lucacrippa88,

Please see my response on the other thread. Thanks!

Hi @thinkingserious
I have a 400 error.
please help me.

$personalization = new SendGrid\Personalization();
$personalization->addCustomArg("meeting_name","myMeetingNameHere");

$myPDF = './myfile.pdf';
    $myPDF_encoded = base64_encode(file_get_contents($myPDF));

    $attachment = new SendGrid\Attachment();
$attachment->setType("application/pdf");
    $attachment->setContent($myPDF_encoded);

$mail = new SendGrid\Mail($from, $subject, $to, $content);
$mail->addPersonalization($personalization);
$mail->addAttachment($attachment);

Thanks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

micahwalter picture micahwalter  路  3Comments

iamanupammaity picture iamanupammaity  路  4Comments

morazain picture morazain  路  3Comments

FilipLukac picture FilipLukac  路  4Comments

KayakinKoder picture KayakinKoder  路  5Comments