I've written a function to send emails using SendGrid's PHP library. It works everywhere except when I try to use it on a form submit event.
When clicking submit I get an error
Fatal error: Class 'SendGrid' not found in ... on line 72
Everything else on submit works fine, the post is added to the database, but the email isn't sent out.
Here is the function
function send_email( $post_id, $templatecode ) {
$substitutions = '
"-FNAME-" : "'.$primary_firstname.'",
"-NAME-" : "'.$primary_name.'",
"-EMAIL-" : "'.$primary_email.'"
';
$to = '
"email": "'.$primary_email.'",
"name": "'.$primary_name.'"
';
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$request_body = json_decode('{
"personalizations": [ {
"substitutions": {'.$substitutions.'},
"to": [ { '.$to.'} ]
} ],
"template_id": "'.$template.'",
"categories": [
"'.$templatecode.'"
],
"from": {
"email": "xxxx",
"name": "xxxxx"
}
}');
$response = $sg->client->mail()->send()->post($request_body);
}
}
Here is the submit action
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
$new_post = array(
'post_title' => wp_strip_all_tags( $_POST['title'] ),
'post_content' => $_POST['description'],
'post_status' => 'publish',
'post_type' => 'sessions'
);
$post_id = wp_insert_post($new_post);
send_email( $post_id, 'Submit' );
}