使用 Gmail API 以 PHP 格式阅读来自 Gmail 的邮件

2022-08-30 19:52:39

我已经从Google PHP客户端库中加载了新的Gmail API源代码。

我通过以下方式启动了该服务:

set_include_path("./google-api-php-client-master/src/".PATH_SEPARATOR.get_include_path());
    
require_once 'Google/Client.php';   
require_once 'Google/Service/Gmail.php';

$client = new Google_Client();
$client->setClientId($this->config->item('gmailapi_clientid'));
$client->setClientSecret($this->config->item('gmailapi_clientsecret'));
$client->setRedirectUri(base_url('auth'));
$client->addScope('email');
//$client->addScope('profile');     
$client->addScope('https://mail.google.com');           
$client->setAccessType('offline');

$gmailService = new Google_Service_Gmail($client);

接下来我该怎么办?如何使用Gmail API PHP库阅读Gmail邮件?


答案 1

为了便于演示,您可以执行如下操作:

$optParams = [];
$optParams['maxResults'] = 5; // Return Only 5 Messages
$optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
$messages = $service->users_messages->listUsersMessages('me',$optParams);
$list = $messages->getMessages();
$messageId = $list[0]->getId(); // Grab first Message


$optParamsGet = [];
$optParamsGet['format'] = 'full'; // Display message in payload
$message = $service->users_messages->get('me',$messageId,$optParamsGet);
$messagePayload = $message->getPayload();
$headers = $message->getPayload()->getHeaders();
$parts = $message->getPayload()->getParts();

$body = $parts[0]['body'];
$rawData = $body->data;
$sanitizedData = strtr($rawData,'-_', '+/');
$decodedMessage = base64_decode($sanitizedData);

var_dump($decodedMessage);

答案 2

这是完整的功能,你可以使用它,因为它工作正常。

session_start();
$this->load->library('google');
$client = new Google_Client();
$client->setApplicationName('API Project');
$client->setScopes(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));
//Web Applicaion (json)
$client->setAuthConfigFile('key/client_secret_105219sfdf2456244-bi3lasgl0qbgu5hgedg9adsdfvqmds5c0rkll.apps.googleusercontent.com.json');

$client->setAccessType('offline');       

// Redirect the URL after OAuth
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

// If Access Toket is not set, show the OAuth URL
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
} else {
    $authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken()) {

    $_SESSION['access_token'] = $client->getAccessToken();
 
    // Prepare the message in message/rfc822
    try {
 
        // The message needs to be encoded in Base64URL

        $service = new Google_Service_Gmail($client);

        $optParams = [];
        $optParams['maxResults'] = 5; // Return Only 5 Messages
        $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
        $messages = $service->users_messages->listUsersMessages('me',$optParams);
        $list = $messages->getMessages();
        $messageId = $list[0]->getId(); // Grab first Message


        $optParamsGet = [];
        $optParamsGet['format'] = 'full'; // Display message in payload
        $message = $service->users_messages->get('me',$messageId,$optParamsGet);
        $messagePayload = $message->getPayload();
        $headers = $message->getPayload()->getHeaders();
        $parts = $message->getPayload()->getParts();

        $body = $parts[0]['body'];
        $rawData = $body->data;
        $sanitizedData = strtr($rawData,'-_', '+/');
        $decodedMessage = base64_decode($sanitizedData);

        var_dump($decodedMessage);
 
    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['access_token']);
    }
 
}

// If there is no access token, there will show url
if ( isset ( $authUrl ) ) { 
    echo $authUrl;
}

推荐