Google Gmail API - 如何以编程方式登录?

sim*_*w16 4 php google-api google-oauth gmail-api

我正在寻找编写一个 PHP 脚本来扫描我的 gmail 收件箱,并阅读未读的电子邮件。不需要用户交互。这必须发生在执行 PHP 文件的 cronjob 上。

这甚至可以通过 API 实现吗?Google 的文档绝对糟糕透了,似乎没有任何示例可以让您以编程方式授权登录。他们总是要求用户在 oauth 请求上物理按下允许按钮。

有没有人尝试过简单地登录并列出您的消息而无需人工交互的经验?

DaI*_*mTo 5

客户登录

我认为您在这里要问的是如何使用您的登录名和密码登录到 api。答案是你不能这被称为客户端登录,谷歌在 2015 年关闭了该选项。如果你想连接到 gmail api,你别无选择,只能使用 Oauth2

服务帐户

通常我会说您应该使用服务帐户。但是,如果您有 gsuite 帐户,则服务帐户仅适用于 gmail,在这种情况下,您可以在此处设置域范围的委托

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
Run Code Online (Sandbox Code Playgroud)

otuh2

如果您没有使用 gsuite。然后您可以做的是对您的代码进行一次验证。确保请求离线访问。刷新令牌将返回给您。如果您保存此刷新令牌,则可以随时使用该刷新令牌来请求新的访问令牌。在下面的示例中,您可以看到刷新令牌如何简单地存储在会话变量中,您可以将其存储在文件中,并在需要时从中读取。

function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
Run Code Online (Sandbox Code Playgroud)

Oauth2Authentication.php撕下的代码

smtp

您提到您想使用 gmail api,但您是否考虑过直接通过邮件服务器?这将允许您使用登录名和密码。或 oauth -> Imap-smtp