简体   繁体   中英

How to send email using send grid from php?

I want to send mail from php. I am trying to use send grid. I followed this link : https://github.com/sendgrid/sendgrid-php

I tried to follow each step. I have downloaded the library not using composer. So added the library in php and written the sample code.

But I am not getting any response or anything in postman, tried to return request body,response tried to echo variables, but not getting anything in result.

    <?php

namespace SendGrid;
//require 'vendor/autoload.php';
require("C:\Users\Siddhi\Downloads\sendgrid-php\sendgrid-php");

class SendEmail
{
    private $db;

    function SendEmail($database){
        $this->db = $database;
    }

    function helloEmail()
    {
        $from = new Email(null, "siddhijambhale@gmail.com");
        $subject = "Hello World from the SendGrid PHP Library";
        $to = new Email(null, "siddhijambhale@gmail.com");
        $content = new Content("text/plain", "send grid test email");
        $mail = new Mail($from, $subject, $to, $content);
        $to = new Email(null, "siddhijambhale@gmail.com");
        $mail->personalization[0]->addTo($to);
        //echo json_encode($mail, JSON_PRETTY_PRINT), "\n";

        echo $to;
        return $mail;
    }

    function sendHelloEmail()
    {
        $apiKey = getenv('PUT-KEY-HERE');
        $sg = new SendEmail($apiKey);
        $request_body = $this->helloEmail();
        $response = $sg->client->mail()->send()->post($request_body);
        echo $response->statusCode();
        echo $response->body();
        echo $response->headers();

        return $request_body;
    }
}

I also tried second way shown in link using composer. So I gave path of a composer.

 <?php

namespace SendGrid;
require 'C:/Program Files (x86)/Ampps/www/testslim/v1/src/vendor/autoload.php';
//require("C:/Users/Siddhi/Downloads/sendgrid-php/sendgrid-php");

class SendEmail
{
    private $db;


    function sendEmail($database) {
        $this->db = $database;
    }

    function helloEmail()
    {
        $from = new Email(null, "siddhijambhale@gmail.com");
        $subject = "Hello World from the SendGrid PHP Library";
        $to = new Email(null, "siddhijambhale@gmail.com");
        $content = new Content("text/plain", "send grid test email");
        $mail = new Mail($from, $subject, $to, $content);
        $to = new Email(null, "siddhijambhale@gmail.com");
        $mail->personalization[0]->addTo($to);
        //echo json_encode($mail, JSON_PRETTY_PRINT), "\n";

        echo $from.$to;

        return $mail;
    }

    function sendHelloEmail()
    {
        $apiKey = getenv('PUT-KEY-HERE');
        $sg = new SendEmail($apiKey);
        echo $apiKey;
        $request_body = $this->helloEmail();
        $response = $sg->client->mail()->send()->post($request_body);
        echo $response->statusCode();
        echo $response->body();
        echo $response->headers();

        return $request_body;
    }
}

By this also it is not giving any result, it also blocks my other url's they are not giving the output.

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';
include '../classes/CustomerOrders.php';
include '../classes/ActivatedMerchants.php';
include '../classes/UserAuthentication.php';
include '../classes/UserActivationItem.php';
include '../classes/CustOtpConfirmation.php';
include '../classes/CustomerRegistrationItems.php';
include '../classes/DeviceToken.php';
include '../classes/SearchMerchants.php';
include '../classes/SendActivationRequest.php';
include '../classes/CustomerBills.php';
include '../classes/CustomerRegistration.php';
include '../classes/ItemsUnits.php';
include '../classes/SendEmail.php';

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$config['db']['host']   = "localhost";
$config['db']['user']   = "kiranadb";
$config['db']['pass']   = "kirana@12345";
$config['db']['dbname'] = "kiranadb";


$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();

$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('my_logger');
    $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
    $logger->pushHandler($file_handler);
    return $logger;
};

$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO("mysql:host=" . $db['host'] . ";dbname=" . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};


$app->get('/getcustorders/[{orderFrom}]', function ($request, $response, $args) {
    $headers = apache_request_headers();
    $customerOrders=new CustomerOrders($this->db);
    $result= $customerOrders->fetchOrders($args['orderFrom'],$headers['Authorization']);
    return $this->response->withJson($result);
});


$app->post('/confirmCustomerOTP', function ($request, $response) {

    $input = $request->getParsedBody();
    $data = [];
    $data['otp'] = filter_var($input['otp'], FILTER_SANITIZE_STRING);
    $data['email_id'] = filter_var($input['email_id'], FILTER_SANITIZE_STRING);
//    $activateUser=new CustomerRegistrationItems($data);
    $custOtpConfirmation=new CustOtpConfirmation($this->db);
    $result= $custOtpConfirmation->activateUserStatus($input['otp'],$input['email_id']);
    return $response = $response->withJson($result);
});

$app->post('/sendCustomerOTP', function ($request, $response) {

    $input = $request->getParsedBody();
    $reg_data = [];
    $reg_data['phone_no'] = filter_var($input['phone_no'], FILTER_SANITIZE_STRING);
    $reg_data['email_id'] = filter_var($input['email_id'], FILTER_SANITIZE_STRING);
   // $mobileno=new CustomerRegistrationItems($reg_data);
    $custOtpConfirmation=new CustOtpConfirmation($this->db);
    $result= $custOtpConfirmation->sendSms($input['phone_no'],$input['email_id']);
    return $response = $response->withJson($result);
});

$app->get('/getactivatedmerchants/[{customer_id}]', function ($request, $response, $args) {

    $headers = apache_request_headers();
    $activatedMerchants=new ActivatedMerchants($this->db);
    $result= $activatedMerchants->fetchMerchants($args['customer_id'],$headers['Authorization']);
    return $this->response->withJson($result);
});

$app->post('/getSearchedMerchants', function ($request, $response, $args) {

    $input = $request->getParsedBody();
    $headers = apache_request_headers();
    $searchMerchant = new SearchMerchants($this->db);
    $result= $searchMerchant->fetchMerchants($input['customer_id'],$headers['Authorization'],$input['latitude'],$input['longitude']);
    return $this->response->withJson($result);
});



$app->post('/sendMail', function ($request, $response, $args) {
    $headers = apache_request_headers();
    $input = $request->getParsedBody();
    $sendMails=new \SendGrid\SendEmail($this->db);
    $result = $sendMails->sendHelloEmail();
    return $this->response->withJson($result);
});

$app->run();

This is api1.php which has url for sendEMail. I am using slim framework in php.

what's going wrong?? Please help..Thank you..

First, change the line

require("C:\Users\Siddhi\Downloads\sendgrid-php\sendgrid-php");

to

require("C:\Users\Siddhi\Downloads\sendgrid-php\sendgrid-php.php");

Now it will be a correct absolute path to the index file of the library.

Note : However, you should avoid using absolute paths.

After this, change

$sg = new SendEmail($apiKey);

to

$sg = new \SendGrid($apiKey);

As it is the correct SendGrid instance you must pass. Currently, you are creating a SendEmail instance with your API key.

Now, It should work.

Here is a basic send with sendgrid

$sendgrid = new SendGrid($key);
$email = new SendGrid\Email();
$email
  ->addTo($to,$toName)
  ->setFrom($from)
  ->setFromName($fromName)
  ->setSubject($subject)
  ->setText('Hello World!')
  ->setHtml($html);

try {
  $sendgrid->send($email);
} catch(\SendGrid\Exception $e) {
}

Amend this line

From

require("C:\Users\Siddhi\Downloads\sendgrid-php\sendgrid-php");

To

require("C:/Users/Siddhi/Downloads/sendgrid-php/sendgrid-php");

Also there may be a typo in here

require("C:/Users/Siddhi/Downloads/sendgrid-php/sendgrid-php");
                                // should this be a dot ^

The DOS backslash is the escape character remember, and should never be used on anything PHP. PHP on Windows will automatically convert the Unix forward slash to what ever is required on a windows system.

But I have to say, you should move this code to your web server folders and not have it in C:users if for no other reason, when you come to copy this to a live host, this will trip you up and you will forget to move this code, but more importantly this data structure will not exist ona unix OS and will not be available to you on a Windows server

Try this it will work:

    <?php

namespace SendGrid;
//require 'vendor/autoload.php';
require("C:\Users\Siddhi\Downloads\sendgrid-php\sendgrid-php.php");
class SendEmail
{
    private $db;

    function SendEmail($database){
        $this->db = $database;
    }

    function helloEmail()
    {
        $from = new Email(null, "siddhijambhale@gmail.com");
        $subject = "Hello World from the SendGrid PHP Library";
        $to = new Email(null, "siddhijambhale@gmail.com");
        $content = new Content("text/plain", "send grid test email");
        $mail = new Mail($from, $subject, $to, $content);
        $to = new Email(null, "siddhijambhale@gmail.com");
        $mail->personalization[0]->addTo($to);
        //echo json_encode($mail, JSON_PRETTY_PRINT), "\n";

        echo $to;
        return $mail;
    }

    function sendHelloEmail()
    {
        $apiKey = getenv('PUT-KEY-HERE');
        $sg = new \SendGrid($apiKey);
        $request_body = $this->helloEmail();
        $response = $sg->client->mail()->send()->post($request_body);
        echo $response->statusCode();
        echo $response->body();
        echo $response->headers();

        return $request_body;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM