I appreciate this has been asked before, but I'm new to both PHP and PaaS, and don't quite see how their example is going to help me.
I have the apache-php-buildpack up and running, I created a SendGrid service and used the graphical interface to bind the service to my application. However, how do I translate that simple PHP one-liner that just sends a form via email into something that works on BlueMix?
With sendmail, it used to be so easy...
if (mail($to, $subject, $body, $headers, "-f " . $_POST['email']))
{
echo 'Thank you.';
}
I understand how to get my SendGrid credentials from the VCAP_SERVICES, as described by in the aforementioned post, but where from here?
Any hints and especially code examples much appreciated!
Answer by Brian K. Martin (5161) | Aug 06, 2014 at 03:25 PM
SendGrid has a very nice set of docs including a live sample builder available here: https://sendgrid.com/docs/code_workshop.html
You can select PHP and it will generate a code template for you
You would not believe how much time I spent on their website today WITHOUT seeing that one...
Answer by badryan (41) | Aug 11, 2014 at 11:10 AM
For future reference, this is a piece of code that works for me: (the required autoload.php and SendGrid.php come from the user's side, and I used composer to install them).
<?php
require 'vendor/autoload.php';
require 'vendor/sendgrid/sendgrid/lib/SendGrid.php';
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services,true);
if (isset($services_json["sendgrid"][0]["credentials"])) {
$sendgrid_config = $services_json["sendgrid"][0]["credentials"];
$user = $sendgrid_config["username"];
$pass = $sendgrid_config["password"];
$url = $sendgrid_config["hostname"];
}
$sendgrid = new SendGrid( $user, $pass );
$mail = new SendGrid\Email();
$mail->
setFrom( $_POST['email'] )->
addTo( "recipient@address.com" )->
setSubject( "email from this website" )->
setText( $_POST['email']."\nadded their address to the newsletter" );
$response = $sendgrid->send( $mail );
echo 'Thank you for subscribing.';
}
else
{
echo 'Your e-mail is not valid. Please try again.';
}
?>