user254153
user254153

Reputation: 1883

Send email using Sendgrid api

I am using send grid to email to the server webmail. Following are my code. I wrote this code by following the tutorials. But I get error :

 Warning: rawurlencode() expects parameter 1 to be string, object given in /home/cwtestco/public_html/demo/active-fit-club/sendgrid-php/vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php on line 237

 Warning: Cannot modify header information - headers already sent by (output started at /home/cwtestco/public_html/demo/active-fit-club/sendgrid-php/vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php:237) in /home/cwtestco/public_html/demo/active-fit-club/index.php on line 53

Code :

 if($res != false){
    require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/vendor/autoload.php');
    require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/lib/SendGrid.php');
    require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/lib/SendGrid/Exception.php');

    $message = "Name : $name <br> Email : $email <br> Mobile : $mobile";
    $sendgrid = new SendGrid('myapikey');
    $email = new SendGrid\Email();
    $email
        ->addTo("[email protected]")
        ->setFrom($email)
        ->setSubject("Contact mail")
        ->setHtml($message);

    try {
        $sendgrid->send($email);
        $_SESSION['success'] = true;
        header("location:url");
        exit;
    } catch(\SendGrid\Exception $e) {
        // echo $e->getCode();
        // foreach($e->getErrors() as $er) {
        //     echo $er;
        // }

        header("location:url");
        exit;
    }
}

Upvotes: 0

Views: 1357

Answers (2)

Justin Steele
Justin Steele

Reputation: 2250

Try moving setting the header before setting the SESSION variable and set $_SESSION['success'] to be 'true' instead of true:

    try {
        $sendgrid->send($email);
        header("location:url");            
        $_SESSION['success'] = 'true';
        exit;
    }

Upvotes: 2

Arasan
Arasan

Reputation: 137

im using the below code and its working.

$url = 'https://api.sendgrid.com/';
$apiKey = 'SENDGRID_API_KEY';

//api library from sendgrid
require_once "sendgrid/sendgrid-php.php";

$sendgrid = new SendGrid($apiKey);
$email = new SendGrid\Email();

$email
    ->addTo("[email protected]")
    ->setFromName("Fromname")
    ->setFrom("[email protected]")
    ->setSubject("your subject goes here")
    ->setText('')
    ->setHtml("your email html content goes here");

if($sendgrid->send($email))
    echo "Mail sent";
else
    echo "Failed";

you can get the library files from https://github.com/sendgrid/sendgrid-php

Upvotes: 1

Related Questions