问题
I'm working on a CRM application where all the staff users have a GMail account which is under a same domain. I'm the admin of this domain. Before, I used a custom access for all GMail users in my CRM using IMAP in order to get all the e-mails sent and received by them. For that I asked their GMail passwords that are stored without any encryption in my DB (It's crappy I know). Now, I want to do the same work but with the Google GMail API, and I have some questions :
-Can I achieve what I want (list all the e-mails from GMail for every staff user and also send e-mails throug GMail using the GMail API and a given GMail account) ?
-I'm not sure but I've seen that it could be possible using a "service account" and domain-wide delegation of authority. If it's true, do I need to go through the OAuth 2.0 even when using a "service account" ? Can maybe anybody guide me on a tutorial or show me the workflow to achieve what I want please ? Best could be in PHP. Thanks in advance for reading me !
回答1:
SOLVED !
I'm answering myself, for people who look for this kind of question.
Yes, we're able to list all e-mails from accounts which belong to a same domain. For that we must create a service account with wide-domaine delegation of authority, using the google admin account. It gives you a Json file(*) to download. You put it on your server.
There is nothing to do with OAuth2.0.
Then with this simple piece of code you get the messages from the account you want (in your domain) :
<?php
require_once __DIR__.'/vendor/autoload.php'; // <-- path for the google-api lib autoload
// simple function to get e-mails' headers
function getHeader($headers, $name) {
foreach($headers as $header) {
if($header['name'] == $name) {
return $header['value'];
}
}
}
$user = "myUser@myDomain.com";
putenv('GOOGLE_APPLICATION_CREDENTIALS='path/to/your/credentials.json'); // (*)
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://mail.google.com']);
$client->setSubject($user);
$service = new Google_Service_Gmail($client);
$results = $service-> users_messages->listUsersMessages($user);
foreach($results as $mail){
$message = $service->users_messages->get($user, $mail['id']);
$headers = $message->getPayload()->getHeaders();
$subject = getHeader($headers, 'Subject');
echo $subject."\n";
}
?>
来源:https://stackoverflow.com/questions/41679462/google-gmail-api-service-account-to-list-e-mails-from-several-accounts