Reputation: 1856
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_key
s with newly generated api key name
and key
but mails are not sending.
Upvotes: 2
Views: 6667
Reputation: 1158
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);
Upvotes: 7
Reputation: 9844
To send with an API key, you need to add an Authorization
header to your request. It is an HTTP Basic auth header, meaning it is in the format username:password
, base64 encoded, as a bearer token. You can see an example in the docs.
Upvotes: 3
Reputation: 441
I use the Send Grid php library where I can use username and password OR just the API Key.
Try removing the api_user
line and using the api key with api_key
. It should work.
For more info: https://sendgrid.com/docs/Integrate/Code_Examples/php.html
Upvotes: 1