PHP Google APIs: 获取gmail邮件, php搜索gmail邮件, php gmail api, Gmail to RSS Feed, PHP Google APIs Client Library

用到的工具:

PHP 快速入门 google apis:Google Developers

 

用法:gmail2rss.php

<?php
require 'vendor/autoload.php';  // composer 安装项目后,引入 autoload.php

define('APPLICATION_NAME', 'Gmail To RSS');
define('CREDENTIALS_PATH', '~/.credentials/gmail-to-rss.json');
define('CLIENT_SECRET_PATH', 'client_secret.json'); // 准备 client_secret.json 文件
define('SCOPES', implode(' ', array(
  Google_Service_Gmail::GMAIL_READONLY) //  参考下面表格
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfigFile(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = file_get_contents($credentialsPath);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->authenticate($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, $accessToken);
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();

$service = new Google_Service_Gmail($client);

$user = 'me';

$optParams = array();
$optParams['maxResults'] = 50;
$optParams['q'] = 'label:justcode is:unread'; // gmail查询条件

try {
    $messages = $service->users_messages->listUsersMessages($user, $optParams); // 条件符合的邮件集合

    $list = $messages->getMessages();

    $i = 0;

    foreach($list as $line) {
        $messageId = $line->getId();

        $optParamsGet = array();
        $optParamsGet['format'] = 'full'; // Display message in payload
        try {
            $message = $service->users_messages->get($user, $messageId, $optParamsGet); // 取得单个邮件
            
            $messagePayload = $message->getPayload();

            $headers = $message->getPayload()->getHeaders();

            foreach($headers as $header) {
                $header_ary[$header->getName()] = $header->getValue();  
            }

            $items[$i]['title'] = $header_ary['Subject'];
            $items[$i]['date'] = strtotime($header_ary['Date']);
            $items[$i]['message_id'] = $messageId;

            $body = $message->getPayload()->getBody(); 

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

            $items[$i]['description'] = $decodedMessage;

            $i ++;

        } catch (apiServiceException $e) {
           // Error from the API.
            print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
        } catch (Exception $e) {
            print 'There was a general error : ' . $e->getMessage();
        }
    }


} catch (apiServiceException $e) {
    // Error from the API.
    print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
    print 'There was a general error : ' . $e->getMessage();
}

// RSS 化
date_default_timezone_set("Asia/Tokyo");

use \FeedWriter\ATOM;
$feed = new ATOM;

//登録
$feed->setTitle("justcode");      
$feed->setLink("http://www.example.com/");    
$feed->setDate(new DateTime());       

foreach($items as $tmp_item) {
    $description = mbereg_replace("(https?|ftp)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "<a href=\"\\1\\2\" target=\"_blank\">\\1\\2</a>" , $tmp_item['description']);
    $description = nl2br($description);
        
    $item = $feed->createNewItem();
    $item->setTitle($tmp_item['title']);
    $item->setLink('http://www.example.com/archive.php?message_id=' . $tmp_item['message_id']);
    $item->setDate($tmp_item['date']);
    $item->setDescription($description);
    $feed->addItem($item);
}


file_put_contents('/path/to/justcode.rdf', $feed->generateFeed()); // ファイルに書き出す
?>

并将其上传到用适当的名称服务器,请将CREDENTIALS_PATH或CLIENT_SECRET_PATH指定的位置设置为不可见的位置。

在终端打开:

php gmail2rss.php

第一次运行,会出现一个授权链接:

Open the following link in your browser: https://〜

请从浏览器访问指定的URL。将出现一个对话框,询问您是否要为此脚本授予权限,因此如果您允许,则会显示代码。复制并返回终端

Enter verification code:

接着,脚本执行,指定位置RSS生成此文件。

PHP Google APIs: 获取gmail邮件, php搜索gmail邮件, php gmail api, Gmail to RSS Feed, PHP Google APIs Client Library
PHP Google APIs: 获取gmail邮件, php搜索gmail邮件, php gmail api, Gmail to RSS Feed, PHP Google APIs Client Library

Gmail scopes

The Gmail API supports the following scopes:

Scope Code Description
https://www.googleapis.com/auth/gmail.readonly Read all resources and their metadata—no write operations.
https://www.googleapis.com/auth/gmail.compose Create, read, update, and delete drafts. Send messages and drafts.
https://www.googleapis.com/auth/gmail.send Send messages only. No read or modify privileges on mailbox.
https://www.googleapis.com/auth/gmail.insert Insert and import messages only.
https://www.googleapis.com/auth/gmail.labels Create, read, update, and delete labels only.
https://www.googleapis.com/auth/gmail.modify All read/write operations except immediate, permanent deletion of threads and messages, bypassing Trash.
https://www.googleapis.com/auth/gmail.metadata Read resources metadata including labels, history records, and email message headers, but not the message body or attachments.
https://www.googleapis.com/auth/gmail.settings.basic Manage basic mail settings.
https://www.googleapis.com/auth/gmail.settings.sharing Manage sensitive mail settings, including forwarding rules and aliases.

Note:Operations guarded by this scope are restricted to administrative use only. They are only available to G Suite customers using a service account with domain-wide delegation.

https://mail.google.com/ Full access to the account, including permanent deletion of threads and messages. This scope should only be requested if your application needs to immediately and permanently delete threads and messages, bypassing Trash; all other actions can be performed with less permissive scopes.

 

 

本文:PHP Google APIs: 获取gmail邮件, php搜索gmail邮件, php gmail api, Gmail to RSS Feed, PHP Google APIs Client Library