如何使用发送网格从PHP发送电子邮件?

时间:2017-01-25 13:27:41

标签: php email sendgrid

我想从php发送邮件。我正在尝试使用发送网格。我按照这个链接: https://github.com/sendgrid/sendgrid-php

我试着按照每一步。我没有使用作曲家下载了这个库。所以在php中添加了库并编写了示例代码。

但我没有得到邮递员的任何回复或任何东西,试图返回请求正文,响应试图回显变量,但没有得到任何结果。

    <?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;
    }
}

我还尝试使用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;
    }
}

由此也没有给出任何结果,它也阻止了我的其他网址,他们没有给出输出。

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();

这是api1.php,其中包含sendEMail的url。我在php中使用slim框架。

出了什么问题?请帮忙..谢谢..

4 个答案:

答案 0 :(得分:3)

首先,更改行

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

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

现在它将成为库的索引文件的正确绝对路径。

注意:但是,您应该避免使用绝对路径。

在此之后,更改

$sg = new SendEmail($apiKey);

$sg = new \SendGrid($apiKey);

因为它是正确的SendGrid实例,所以必须通过。目前,您正在使用API​​密钥创建SendEmail实例。

现在,它应该工作。

答案 1 :(得分:1)

这是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) {
}

答案 2 :(得分:0)

修改此行

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

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

此处可能还有拼写错误

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

DOS反斜杠是逃避字符的记忆,永远不应该用在任何PHP上。 Windows上的PHP会自动将Unix正斜杠转换为Windows系统所需的斜杠。

  

但我必须说,您应该将此代码移至您的网络服务器文件夹而不是C:users,如果没有其他原因,当您将其复制到现场主机时,这会让您失望您将忘记移动此代码,但更重要的是,此数据结构将不会存在于unix操作系统上,并且在Windows服务器上无法使用

答案 3 :(得分:0)

试试这个会起作用:

    <?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;
    }
}