如何将Sengrid API与CI集成为库

时间:2019-04-22 18:40:28

标签: php codeigniter sendgrid

我的应用程序正在与CI一起运行,并且为了发送电子邮件,我使用的是Sendgrid API。

我的想法是将SendGrid API用作库,因此可以像这样加载它: $this->load->library('my_ci_lib');

搜索一些示例,我发现的唯一结果是在Native CI Email库中设置Sendgrid SMTP配置并对其进行扩展。

如何在CI中使用Sendgrid API?

这是我以前在原始PHP中使用Sendgrid API的地方:

<?php
require_once('../../class/SendGrid/sendgrid-php.php');

function welcomeEmail($email, $firstName, $password){
    require_once('_key.php');
    $chaves = array('{name}', '{key}');
    $template = utf8_decode(file_get_contents('../../templates/welcomePass.html'));
    $template = str_replace($chaves, array(utf8_decode($firstName), $password), $template);

    // $mail->SetFrom('no-reply'.rand(1, 100).'@domain.com.br', 'Domain');
    // $mail->Subject = utf8_decode('Seja bem-vindo(a)!');
    // $mail->Body = $template;
    // $mail->isHTML(true);
    // $mail->addTo($email);
    // //$mail->SMTPDebug = 3;

    $mail = new \SendGrid\Mail\Mail();
    $mail->setFrom("connectz.no-reply".rand(1, 100)."@domain.com.br", "CONNECTZ");
    $mail->setSubject("Seja bem-vindo(a)!");
    $mail->addTo($email);
    $mail->addBcc("joao.souza@domain.com.br");
    $mail->addContent("text/html", utf8_encode($template));
    $sendgrid = new \SendGrid($key);

    $response = $sendgrid->send($mail);
    // print $response->statusCode() . "<br>";
    // echo '<pre>'.print_r($response->headers()).'</pre><br>';
    // print $response->body() . "";
}

1 个答案:

答案 0 :(得分:0)

所以这可能不是最好的方法,但是我必须执行以下操作才能将Cloudinary和MongoDB集成到基于CodeIgniter的站点中。

在文件夹application/library中,我创建了一个文件Cloudinarylib.php,其中包含一个名为cloudinary的文件夹,其中包含所有必需的文件。

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

/**
 * This is a "dummy" library that just loads the actual library in the construct.
 * This technique prevents issues from CodeIgniter 3 when loading libraries that use PHP namespaces.
 * This file can be used with any PHP library that uses namespaces.  Just copy it, change the name of the class to match your library
 * and configs and go to town.
 */

class Cloudinarylib
{
    public function __construct()
    {
        $this->CI =& get_instance();

        // include the cloudinary library within the dummy class
        require('cloudinary/src/Cloudinary.php');
        require('cloudinary/src/Uploader.php');
        require('cloudinary/src/Api.php');

        // configure Cloudinary API connection
        \Cloudinary::config($this->CI->config->item('cloudinary'));
    }
}

然后,我可以使用$this->load->library('cloudinarylib');加载库并运行\Cloudinary\Uploader::upload("https://www.example.com/uploads/".$file);之类的脚本

我希望这会有所帮助。