Send email with SendGrid from PHP (sendgrid-php v8)
The exact working pattern for sendgrid-php: composer install, the Mail builder methods, and reading statusCode off the response inside a try/catch. Not the full reference manual.
TL;DR: The exact working pattern for sendgrid-php: composer install, the Mail builder methods, and reading statusCode off the response inside a try/catch. Install: composer require sendgrid/sendgrid. Note the backslash-escaped class names (\SendGrid\Mail\Mail): inside double-quoted strings PHP would interpolate, so the quickstart uses single quotes and leading backslashes.
The fix
- Install: composer require sendgrid/sendgrid.
- Build and send: require 'vendor/autoload.php'; use \SendGrid\Mail\Mail; $email = new Mail(); $email->setFrom('[YOURVERIFIEDSENDER]', 'Your Name'); // verified sender $email->setSubject('subject here'); $email->addTo('[RECIPIENTEMAIL]', 'Their Name'); $email->addContent('text/plain', 'plain body'); $email->addContent('text/html', '[strong]html body[/strong]'); $sendgrid = new \SendGrid(getenv('SENDGRIDAPI_KEY')); try { $response = $sendgrid->send($email); printf("Response status: %d\n", $response->statusCode()); // 202 means accepted } catch (Exception $e) { echo 'Caught exception: ' . $e->getMessage() . "\n"; }
- Note the backslash-escaped class names (\SendGrid\Mail\Mail): inside double-quoted strings PHP would interpolate, so the quickstart uses single quotes and leading backslashes.
- The from address must be a verified sender or the send fails.
- Read the key from the environment with getenv. Do not commit it, and do not echo it in error output.
When to use this
- This covers exactly what the title says: Send email with SendGrid from PHP (sendgrid-php v8).
- You are setting this up for the first time, or auditing an existing setup.
- You want the key gotchas in one place before you start.
When not to use this
- You are doing a different workflow with Send; these steps are specific to the title above.
- You need the full reference docs; this is the short path, not the manual.
Compatibility
- Not pinned to a specific version; follows current Send behavior.