art art - 6 months ago 467
PHP Question

Wrong credentials in sending mail using sendgrid

This is the code for sending email using sendgrid i have correct api key still the browser displays error as

HTTP/1.1 401 Unauthorized Server: nginx Date: Thu, 14 Jul 2016 08:14:32 GMT Content-Type: application/json Content-Length: 88 Connection: keep-alive {"errors":[{"message":"Permission denied, wrong credentials","field":null,"help":null}]}

require '/sendgrid-php/vendor/autoload.php';
{echo "path found";}

function sendemail($f,$s,$t,$m){

$from = new SendGrid\Email(null, $f);
$subject = $s;
$to = new SendGrid\Email(null, $t);
$content = new SendGrid\Content("text/plain", $m);
$mail = new SendGrid\Mail($from, $subject, $to, $content);

$apiKey = getenv('Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->headers();
echo $response->body();


Looks like you didn't set the environment variable with the api key that you're trying to use with:

$apiKey = getenv(...);

Please check documentation here as it looks like you're using the example code.

Just for a test you can use:

$apiKey = 'add here your api key';

replacing the usage of getenv. It should work. Then you can set the api key in a config file or as env variable (depending on your application) in order to not hardcode it into the script.