Send email using Sendgrid api

时间:2016-08-30 04:26:15

标签: php email sendgrid

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("info@abc.co.uk")
        ->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;
    }
}

2 个答案:

答案 0 :(得分:1)

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("to@example.com")
    ->setFromName("Fromname")
    ->setFrom("from@example.com")
    ->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

答案 1 :(得分:1)

在设置SESSION变量之前尝试移动设置标题,并将$ _SESSION ['success']设置为'true'而不是true:

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