如何通过php使用sendgrid正确发送电子邮件

时间:2019-05-14 02:35:18

标签: php sendgrid

我有下面的代码来自sendgrid,用于使用API​​密钥发送电子邮件,但由于显示,我无法正常工作

  

错误致命错误:未捕获错误:调用成员函数send()   串入...

我已根据需要安装作曲家

但是,$sendgrid->send($email)实际上并没有返回任何内容,因此$ mail是一个空变量。 关于如何解决此问题的任何想法。

Api链接source

<?php

// https://sendgrid.com/docs/API_Reference/index.html

// using SendGrid's PHP Library
// https://github.com/sendgrid/sendgrid-php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
// Comment out the above line if not using Composer
// require("./sendgrid-php.php");
// If not using Composer, uncomment the above line

$email = new \SendGrid\Mail\Mail();
$email->setFrom("test@example.com", "Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("test@example.com", "Example User");
$email->addContent(
    "text/plain", "and easy to do anywhere, even with PHP"
);
$email->addContent(
    "text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
//$sendgrid = new \SendGrid(getenv('my api goes here'));
$sendgrid = 'my api goes here';
try {
    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

1 个答案:

答案 0 :(得分:0)

您正在尝试在字符串上调用函数。

$sendgrid = 'my api goes here';

后来:

$response = $sendgrid->send($email);

我想你的意思是

$response = $email->send($email);