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

时间:2019-05-13 23:01:09

标签: php google-api google-oauth gmail-api

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

使用API​​甚至可以做到吗? Google的文档绝对可怕,而且似乎没有任何示例可以让您以编程方式授权登录。它们始终要求用户在oauth请求上实际按下“允许”按钮。

是否有人在尝试简单地登录和列出您的消息而无需人工干预的经验?

2 个答案:

答案 0 :(得分:1)

客户端登录

我认为您要在此处询问的是如何使用您的登录名和密码登录api。答案是您不能在2015年将其称为“客户端登录”,然后google关闭该选项。如果要连接到gmail api,您别无选择,只能使用Oauth2

服务帐户

通常我会说您应该使用服务帐户。但是,如果您有gsuite帐户,则服务帐户只能与gmail一起使用,在这种情况下,您可以设置域范围的委托的here

// 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();
    }
}

oatuh2

如果您不使用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();
    }
}

Oauth2Authentication.php翻录的代码

smtp

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

答案 1 :(得分:0)

您需要使用三足式OSuth,即OAuth,最终用户(Gmail帐户的所有者)登录并授权您的应用读取他们的电子邮件,OAuth是其中的三者。除了三足式OAuth之外,没有其他方法可以通过API访问用户的Gmail帐户。

最终用户需要第一次单击。一旦您的应用获得了最终用户的同意,该应用将来就可以代表用户访问Gmail API,而无需点击。我发现this文档最清晰,寻找Array.filter

您可以从文档中复制并粘贴一个简单的JavaScript Frontend,该文档使您可以登录并使用PHP编写后端逻辑。