Skip to content

Instantly share code, notes, and snippets.

@brandonmwest
Last active June 25, 2022 13:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brandonmwest/4512396 to your computer and use it in GitHub Desktop.
Save brandonmwest/4512396 to your computer and use it in GitHub Desktop.
curl + PHP example of using the SendGrid web api

This example uses cURL with PHP through our web API to send an email.

<?php $url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD'; 
 
$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'example3@sendgrid.com',
    'subject'   => 'testing from curl',
    'html'      => 'testing body',
    'text'      => 'testing body',
    'from'      => 'example@sendgrid.com',
  );
 
 
$request =  $url.'api/mail.send.json';
 
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
// obtain response
$response = curl_exec($session);
curl_close($session);
 
// print everything out
print_r($response);

An Email Sent Using the SMTPAPI Header

This example takes the previous example a step further by adding our SMTPAPI header to set a category and send out to multiple recipients. The category is called test_category, and the email will go out to both example1@sendgrid.com and example2@sendgrid.com. The normal to address, example3@sendgrid.com, will not receive an email.

<?php 
$url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';
 
$json_string = array(
 
  'to' => array(
    'example1@sendgrid.com', 'example2@sendgrid.com'
  ),
  'category' => 'test_category'
);
 
 
$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'x-smtpapi' => json_encode($json_string),
    'to'        => 'example3@sendgrid.com',
    'subject'   => 'testing from curl',
    'html'      => 'testing body',
    'text'      => 'testing body',
    'from'      => 'example@sendgrid.com',
  );
 
 
$request =  $url.'api/mail.send.json';
 
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
 
// obtain response
$response = curl_exec($session);
curl_close($session);
 
// print everything out
print_r($response);

An Email Sent Including a File Attachment

This example adds the additional attachment parameter to attach a file called myfile. This example assumes the file is in the same directory as your code otherwise you need to specify the full path of the file in the $filePath variable.

<?php 
$url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';

$fileName = 'myfile';
$filePath = dirname(__FILE__);

$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'example@sendgrid.com',
    'subject'   => 'test of file sends',
    'html'      => '<p> the HTML </p>',
    'text'      => 'the plain text',
    'from'      => 'example@sendgrid.com',
    'files['.$fileName.']' => '@'.$filePath.'/'.$fileName
  );

print_r($params);

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);

// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);

// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);

// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
print_r($response);
@smkazim
Copy link

smkazim commented Mar 8, 2017

Hello Sir,
Thank for helping.

but i am confused with api_key and password because at first you have assigned $pass with password but then you assigned api_key with $pass.
my confusion is that password and api_key are same? if that is so then why we generated api_key?

@Aadencoder
Copy link

Aadencoder commented May 26, 2017

Hello Brandon,
Thanks for sharing this usefull information . I have use this method to send email via sendgrid and it works perfect. But now I am stuck with the Event Webhook Notification. I have search, google and read the sendgrid Doc and I not understanding properly. Can please help me how to get Event Web hook Working using PHP..

Thanks
aaden

@howardb3115
Copy link

Hello,

I am having trouble with the file attachment example, where the one file that I am attaching is a 66kb png file that shows up in my email client with a size of 88 bytes. Additionally, I'm trying to use the content array to specify an id for the one attachment, but due to the file being truncated, I'm not sure if the png file is being assigned the right id and would work in the image tag in my html body message.

I would have attached my PHP script, renamed it as a txt file, but the site said 'We don't support that file type' for txt and pdf type files.

Would you please point me to a PHP example that properly sends an image file and displays that image in the html email?

`<?php
//
// https://stackoverflow.com/questions/24079264/integrate-sendgrid-with-symfony2
// https://sendgrid.com/docs/API_Reference/Web_API/mail.html
// https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/php.html
//

function sendgridmail( $from, $fromName, $to, $toname, $subject, $messageText, $messageHTML, $headers ) {
$url = 'https://api.sendgrid.com/';
$user = '';
$pass = '';
$fileName = 'image.png';
$filePath = '<full path to the image.png file not including /image.php>';

$params = array(
    'api_user'                   => $user,
    'api_key'                    => $pass,
    'from'                       => $from,
    'fromname'                   => $fromName,
    'replyto'                    => $from,
    'to'                         => $to,
    'toname'                     => $toname,
    'subject'                    => $subject,
    'html'                       => $messageHTML,
    'text'                       => $messageText,
    'files[' . $fileName . ']'   => '@' . $filePath . '/' . $fileName,
    'content[' . $fileName . ']' => 'ii_139db99fdb5c3704'
);

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init( $request );

// Tell curl to use HTTP POST
curl_setopt( $session, CURLOPT_POST, true );

// Tell curl that this is the body of the POST
curl_setopt( $session, CURLOPT_POSTFIELDS, $params );

// Tell curl not to return headers, but do return the response
curl_setopt( $session, CURLOPT_HEADER, false );

curl_setopt( $session, CURLOPT_RETURNTRANSFER, true );

//print_r('obtaining the response');

// obtain response
$response = curl_exec( $session );
curl_close( $session );

}

//only for testing:

$from = '<sender's email address>';
$fromName = '<sender's name>';
$to = '<receiver's email address>';
$toname = '<receiver's name>';
$subject = 'Testemail';
$messageText = 'It works!!';
$messageHTML = 'It works!!';

sendgridmail( $from, $fromName, $to, $toname, $subject, $messageText, $messageHTML, array() );
?>`

@vasuraghav
Copy link

Hi

whenever i request the curl command it redirects me

301 Moved Permanently
nginx

do you have any idea why is it happening ?

@pr0woKator
Copy link

Sendgrid force https, so you have to change http to https.

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