Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Last active January 28, 2023 15:22
Show Gist options
  • Save keithweaver/08b588d4674d5451e44527cbde99e886 to your computer and use it in GitHub Desktop.
Save keithweaver/08b588d4674d5451e44527cbde99e886 to your computer and use it in GitHub Desktop.
Send an email with PHP using Sendgrid (Mail Server)
<?php
// You need to install the sendgrid client library so run: composer require sendgrid/sendgrid
require '/vendor/autoload.php';
// contains a variable called: $API_KEY that is the API Key.
// You need this API_KEY created on the Sendgrid website.
include_once('./credentials.php');
$FROM_EMAIL = 'YOUR_EMAIL';
// they dont like when it comes from @gmail, prefers business emails
$TO_EMAIL = 'THE_PERSON_YOUR_WANT_TO_CONTACT';
// Try to be nice. Take a look at the anti spam laws. In most cases, you must
// have an unsubscribe. You also cannot be misleading.
$subject = "YOUR_SUBJECT";
$from = new SendGrid\Email(null, $FROM_EMAIL);
$to = new SendGrid\Email(null, $TO_EMAIL);
$htmlContent = '';
// Create Sendgrid content
$content = new SendGrid\Content("text/html",$htmlContent);
// Create a mail object
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$sg = new \SendGrid($API_KEY);
$response = $sg->client->mail()->send()->post($mail);
if ($response->statusCode() == 202) {
// Successfully sent
echo 'done';
} else {
echo 'false';
}
?>
@servericon
Copy link

@

@Baliram12
Copy link

i also got an error Uncaught Error: Class 'SendGrid\Email' not found in:line at 11::Uncaught Error: Class 'SendGrid\Email' not found in

@khokonm
Copy link

khokonm commented Dec 6, 2019

i also got an error Uncaught Error: Class 'SendGrid\Email' not found in:line at 11::Uncaught Error: Class 'SendGrid\Email' not found in

@khyatibhojawala
Copy link

khyatibhojawala commented Mar 12, 2020

I also get the same error

Fatal error: Uncaught Error: Class 'SendGrid\Email' not found in C:\wamp64\www\sendgrid_demo\index.php on line 19
Error: Class 'SendGrid\Email' not found in C:\wamp64\www\sendgrid_demo\index.php on line 19

I have install SDK from composer using composer require sendgrid/sendgrid on the root folder of my project (https://prnt.sc/rf44hj)

`<?php

require 'vendor/autoload.php';
include_once('credentials.php');
$FROM_EMAIL = 'FROM_EMAIL';

$TO_EMAIL = 'TO_EMail';
$subject = "Testing Email";

$from = new SendGrid\Email(null, $FROM_EMAIL);
$to = new SendGrid\Email(null, $TO_EMAIL);

$htmlContent = '<div style="background: red;"> My Company </div>';

$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';
}

?>`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment