Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send mail using send grid api key

Tags:

php

curl

sendgrid

I'm using send grid for sending mails. This is the script I used.

$url = 'https://api.sendgrid.com/';
$params = array(
    'api_user'  => 'xxx',   // My send grid username
    'api_key'   => xxx',   // My send grid password
    'to'        => tomail,     
    'subject'   => 'sub',
    'html'      => 'message',
    'from'      => frommail,
);

$request =  $url.'api/mail.send.json';
$session = curl_init($request);
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);

It's working fine and sending mails successfully.

I wan't to use send grid api key for sending mails without using the password. I generated it from 'app.sendgrid.com/settings/api_keys' got api key id and long key.

How can I use this keys from web api call. I'm replacing api_user and api_keys with newly generated api key name and key but mails are not sending.

like image 712
Gowri Avatar asked Jun 04 '26 18:06

Gowri


1 Answers

I ran into this today as well. To add to the answer provided by @bwest:

$pass = 'your api token' // not the key, but the token

$url = 'https://api.sendgrid.com/';

//remove the user and password params - no longer needed
$params = array(
    'to'        => tomail,     
    'subject'   => 'sub',
    'html'      => 'message',
    'from'      => frommail,
);

$request =  $url.'api/mail.send.json';
$headr = array();
// set authorization header
$headr[] = 'Authorization: Bearer '.$pass;

$session = curl_init($request);
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// add authorization header
curl_setopt($session, CURLOPT_HTTPHEADER,$headr);

$response = curl_exec($session);
curl_close($session);
like image 127
Tom Fast Avatar answered Jun 06 '26 21:06

Tom Fast