繁体   English   中英

使用 Sendgrid API 密钥而不是 Codeigniter 中的 SMTP 发送邮件

[英]Send mail using Sendgrid API key not with SMTP in Codeigniter

我需要什么:我需要使用 Sendgrid API 密钥从 Codeigniter 发送 email。

我展示了下面的示例,使用 SMTP 详细信息以及 codeigniter 中的用户名和密码发送 email。

例子:

在 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';
?>

在 Controller 中:

<?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 密钥发送邮件。 有没有可能做的。

谢谢

这里下载 PHP sendgrid 补丁

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

N:B 如果您使用 Codeigniter 的作曲家,您可以像下面这样添加,您可以使用作曲家更新更新依赖关系,它将使用您的供应商文件夹下载包。

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

一旦在 vendor/sendgrid-php 文件夹中完成 go

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

您可以使用 controller 中的库,如下所示。

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

您将在此处获得更多图书馆文档

暂无
暂无

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

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