简体   繁体   English

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

[英]How to send email using send grid from php?

I want to send mail from php.我想从php发送邮件。 I am trying to use send grid.我正在尝试使用发送网格。 I followed this link : https://github.com/sendgrid/sendgrid-php我跟着这个链接: 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.所以在php中添加了这个库并编写了示例代码。

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.我还尝试了使用 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.通过这种方式,它也没有给出任何结果,它也阻止了我的其他 url,它们没有给出输出。

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.这是 api1.php,它有 sendEMail 的 url。 I am using slim framework in php.我在 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.因为它是正确的 SendGrid 实例,所以您必须通过。 Currently, you are creating a SendEmail instance with your API key.目前,您正在使用 API 密钥创建 SendEmail 实例。

Now, It should work.现在,它应该工作。

Here is a basic send with sendgrid这是使用 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.请记住,DOS 反斜杠是转义字符,不应在任何 PHP 上使用。 PHP on Windows will automatically convert the Unix forward slash to what ever is required on a windows system. Windows 上的 PHP 将自动将 Unix 正斜杠转换为 Windows 系统上所需的内容。

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但是我不得不说,如果没有其他原因,您应该将此代码移动到您的 Web 服务器文件夹中,而不是将它放在C:users ,当您将其复制到实时主机时,这会让您感到困惑,您会忘记移动此代码,但更重要的是,此数据结构在 unix 操作系统上不存在,并且在 Windows 服务器上不可用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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