【问题标题】:Send mail using Sendgrid API key not with SMTP in Codeigniter使用 Sendgrid API 密钥发送邮件,而不是 Codeigniter 中的 SMTP
【发布时间】:2020-07-26 22:44:32
【问题描述】:

我需要什么:我需要使用 Sendgrid API 密钥从 Codeigniter 发送一封电子邮件。

我在下面展示了使用 SMTP 详细信息以及 codeigniter 中的用户名和密码发送电子邮件的示例。

例子:

在 application/config 文件夹中创建一个名为“email.php”的文件,并将以下代码粘贴到其中。

/* application/config/email.php */

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| SendGrid Setup
|--------------------------------------------------------------------------
|
| All we have to do is configure CodeIgniter to send using the SendGrid
| SMTP relay:
*/
$config['protocol'] = 'smtp';
$config['smtp_port']    = '587';
$config['smtp_host']    = 'smtp.sendgrid.net';
$config['smtp_user']    = 'yourusername';
$config['smtp_pass']    = 'yourpassword';
?>

在控制器中:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->library('email');

        $this->email->from('test123@gmail.com', 'John');
        $this->email->to('test123@gmail.com');
        $this->email->subject('Test Email using SendGrid');
        $this->email->message('This email was delivered by your friends at SendGrid');

        $this->email->send();

        echo $this->email->print_debugger();

        $this->load->view('welcome_message');
    }
}
?>

但我需要通过 API 密钥发送邮件。有没有可能做的。

谢谢

【问题讨论】:

  • 你试过这个库了吗github.com/sendgrid/sendgrid-php
  • @MohammedShafeek 是的,我直接在 PHP 中尝试它工作正常。但我不知道如何在 codeigniter 中进行设置。如果你知道,请帮我解决这个问题。

标签: php codeigniter sendgrid-api-v3


【解决方案1】:

HERE下载 PHP sendgrid 补丁

将它放在根目录下的所需文件夹中。

N:B 如果你在 Codeigniter 中使用 composer,你可以像下面这样添加,你可以使用 composer update 更新依赖,它会下载你的供应商文件夹的包。

{
  "require": {
    "sendgrid/sendgrid": "~7"
  }
}

完成后进入 vendor/sendgrid-php 文件夹

在该文件夹内执行composer install 以安装当前库的依赖项。

您可以在控制器中使用库,如下所示。

    require FCPATH .'vendor/sendgrid-php/sendgrid-php.php';

    $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('SENDGRID_API_KEY'));
    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";
    }

您将获得更多库文档HERE

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 2013-10-18
    相关资源
    最近更新 更多