1

This is the code for sending email using sendgrid. I have tried following the directions to the best of my knowledge. It seems like my code is failing at getev($apiKey); which is not returning anything, hence the Unauthorized Access error. How can I get it to work?

<?php

    error_reporting(E_ALL);
    require_once ('../vendor/autoload.php');
    $from = new SendGrid\Email("name","blah@blah.com");
    $subject = "First Test Email Hello World from the SendGrid PHP Library!";
    $to = new SendGrid\Email("another name","blah@gmail.com");
    $content = new SendGrid\Content("text/html", "<h1>Hello, Email!</h1>");
    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $apiKey = getenv('SENDGRID_API_KEY');
    echo "please work";
    echo "API KEY: " . $apiKey . "<br>";      //return nothing :(
    $sg = new \SendGrid($apiKey);

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


?>

I ran these in the root folder and even used export -p where SENDGRID_API_KEY is listed and has been set to my API key.

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

How can I get getenv($apiKey); to work?

Govind Rai
  • 14,406
  • 9
  • 72
  • 83

1 Answers1

0

This guide to what environment variables are and how they work should be clarify a few things: http://www.codecoffee.com/tipsforlinux/articles/030.html

You need to configure your environment (server, shell, etc) with the variable. It does not come from a file. You can temporarily do this in PHP via putenv but the variables will not persist.

bwest
  • 9,182
  • 3
  • 28
  • 58