You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gmail API无需通过SMTP是否可在Codeigniter框架中使用?

可以在Codeigniter框架中完全不依赖SMTP协议,直接通过Gmail API实现邮件发送等需求,具体实现方案如下:

前期准备
  • 登录Google Cloud控制台创建项目,开启Gmail API权限,生成对应OAuth 2.0凭据:如果是需要用户授权的场景选择Web应用类型,配置对应的回调地址;如果是Google Workspace账号的内部服务场景,可以创建服务账号并配置域-wide委派权限,无需用户手动授权。
  • 通过Composer安装Google官方PHP客户端库,执行命令:composer require google/apiclient:^2.0
  • 开启Codeigniter的Composer自动加载:在application/config/config.php中修改配置项$config['composer_autoload'] = FCPATH . 'vendor/autoload.php';,指向你项目中vendor目录下的自动加载文件。
核心实现逻辑

1. 封装Gmail API操作库

在application/libraries目录下新建Gmail_api.php,实现客户端初始化、授权校验、邮件发送等方法,核心代码示例:

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

use Google\Client;
use Google\Service\Gmail;

class Gmail_api {
    protected $CI;
    protected $google_client;
    protected $gmail_service;

    public function __construct() {
        $this->CI =& get_instance();
        // 初始化Google客户端
        $this->google_client = new Client();
        $this->google_client->setClientId('你的CLIENT_ID');
        $this->google_client->setClientSecret('你的CLIENT_SECRET');
        $this->google_client->setRedirectUri('你的回调地址');
        $this->google_client->addScope('https://www.googleapis.com/auth/gmail.send');
        $this->google_client->setAccessType('offline');
        $this->google_client->setPrompt('select_account consent');

        // 读取已存储的access token,可根据需求改为从数据库读取
        $tokenPath = APPPATH . 'config/gmail_token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $this->google_client->setAccessToken($accessToken);
        }

        // 自动刷新过期token
        if ($this->google_client->isAccessTokenExpired()) {
            if ($this->google_client->getRefreshToken()) {
                $accessToken = $this->google_client->fetchAccessTokenWithRefreshToken($this->google_client->getRefreshToken());
                file_put_contents($tokenPath, json_encode($accessToken));
            }
        }

        $this->gmail_service = new Gmail($this->google_client);
    }

    // 构造base64url编码的邮件内容
    protected function create_message($to, $subject, $bodyText, $from = '') {
        $rawMessage = "From: {$from}\r\n";
        $rawMessage .= "To: {$to}\r\n";
        $rawMessage .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
        $rawMessage .= "MIME-Version: 1.0\r\n";
        $rawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
        $rawMessage .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $rawMessage .= base64_encode($bodyText);

        // 转换为Gmail要求的base64url格式
        $rawMessage = strtr(base64_encode($rawMessage), array('+' => '-', '/' => '_'));
        return $rawMessage;
    }

    // 发送邮件方法
    public function send_mail($to, $subject, $body, $from) {
        $message = new \Google\Service\Gmail\Message();
        $message->setRaw($this->create_message($to, $subject, $body, $from));
        return $this->gmail_service->users_messages->send('me', $message);
    }

    // 获取授权地址,首次授权时调用
    public function get_auth_url() {
        return $this->google_client->createAuthUrl();
    }

    // 回调时用授权码换取token
    public function fetch_token_with_code($code) {
        $accessToken = $this->google_client->fetchAccessTokenWithAuthCode($code);
        $tokenPath = APPPATH . 'config/gmail_token.json';
        file_put_contents($tokenPath, json_encode($accessToken));
        return $accessToken;
    }
}

2. 控制器中调用示例

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

class Gmail_test extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('gmail_api');
    }

    // 首次授权入口
    public function auth() {
        if (!$this->gmail_api->google_client->getAccessToken()) {
            redirect($this->gmail_api->get_auth_url());
        } else {
            redirect('gmail_test/send');
        }
    }

    // 授权回调地址
    public function oauth2callback() {
        if (isset($_GET['code'])) {
            $this->gmail_api->fetch_token_with_code($_GET['code']);
            redirect('gmail_test/send');
        }
    }

    // 发信测试
    public function send() {
        try {
            $result = $this->gmail_api->send_mail(
                '收件人邮箱地址',
                '测试邮件主题',
                '<h1>这是Gmail API发送的测试邮件内容</h1>',
                '你的发件人邮箱地址'
            );
            echo "邮件发送成功,ID:" . $result->getId();
        } catch (Exception $e) {
            echo "发送失败:" . $e->getMessage();
        }
    }
}
注意事项
  • 普通个人Gmail账号无法使用服务账号模式,必须走一次OAuth2授权流程,获取到refresh token后后续可以自动刷新,无需重复授权。
  • 发件人地址必须为授权账号对应的邮箱,否则会触发权限错误。
  • 敏感信息如CLIENT_ID、CLIENT_SECRET、refresh token不要硬编码在代码中,建议存储在环境变量或独立的配置文件中,做好权限控制。
  • 需要发送附件的场景可以扩展create_message方法,按照标准MIME格式拼接附件内容即可,Gmail API可直接识别。

内容的提问来源于stack exchange,提问作者Abdullah Ashraf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:36:05