Chris Buckley
Chris Buckley

Reputation: 35

How to send email using SendGrid

I have been trying to set up email for a web page using SendGrid's PHP API, and I'm having no luck. I have tried their code from the Azure website as well as various examples I found while trying to Google it, and every time it returns nothing as a response, and the email isn't set. Here is the code I'm talking about:

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

 $params = array(
      'api_user' => $user,
      'api_key' => $pass,
      'to' => '[email protected]',
      'subject' => 'testing from curl',
      'html' => 'testing body',
      'text' => 'testing body',
      'from' => '[email protected]',
   ); 

 $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);
 ?>

It is also worth noting that I've tried using sendgrid-php accompanied with the code supplied with it, and that causes the page to simply not load. I'm really stumped right now, and any help is greatly appreciated.

Upvotes: 2

Views: 896

Answers (2)

Gary Liu
Gary Liu

Reputation: 13918

By default, Azure doesn't generate a SSL peer certificate for Azure Web Apps. If you add the code in your test code $error = curl_error($session);, you will get the error SSL certificate problem: self signed certificate in certificate chain.

You can simply add the code curl_setopt($session, CURLOPT_SSL_VERIFYPEER, 0); to bypass the verification.

Otherwise, you can follow Verify Peer Certificate from PHP cURL for Azure Apps to add a certificate on Azure Web Apps.

Upvotes: 1

Andrew Shell
Andrew Shell

Reputation: 1080

It's possible your version of cURL doesn't support SSL out of the box.

You can test this by putting the following at the top of your code:

if (!curl_version()['features'] & CURL_VERSION_SSL) {
    echo "SSL is not supported with this cURL installation.";
}

If it's not supported out of the box you have to configure it manually like this:

curl_setopt($session, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, 2);
// path to CA certificate
curl_setopt($session, CURLOPT_CAINFO, '/etc/openssl/cert.pem'); 

Upvotes: 0

Related Questions