Synchronized GMail Inbox [PHP]

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
use Carbon\Carbon;
use Illuminate\Console\Command;

class GMailSync extends Command
{

    private $mailService;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'google:sync-email';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run to synchronize google emails';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(GMailServiceInterface $mailService)
    {
        parent::__construct();
        $this->mailService = $mailService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $client = $this->getClient();
        $service = new \Google_Service_Gmail($client);
        $user = 'me';
        $opt_param = ['labelIds' => 'INBOX'];
        $messages = $service->users_messages->listUsersMessages($user, $opt_param);
        $bar = $this->output->createProgressBar(count($messages));
        foreach ($messages as $key => $message) {
            $message = $service->users_messages->get($user, $message->getId(), ['format' => 'full']);
            $this->mailService->create([
                'email_id' => $message->getId(),
                'snippet' => $message->getSnippet(),
                'headers' => json_encode($message->getPayload()->getHeaders()),
                'body' => (!empty($message->getPayload()->getBody()->getData()) ?
                    $message->getPayload()->getBody()->getData() : $message->getPayload()->getParts()[1]->body->data),
                'internal_date' => Carbon::createFromTimestamp($message->getInternalDate() / 1000)
                    ->toDateTimeString()
            ]);

            $bar->advance();
        }
        $bar->finish();
    }

    private function googleScopes()
    {
        return implode(' ', [
            \Google_Service_Gmail::MAIL_GOOGLE_COM,
        ]);
    }

    private function getClient()
    {
        $client = new \Google_Client();
        $client->setApplicationName(getenv('APP_NAME'));
        $client->setScopes($this->googleScopes());
        $client->setAuthConfig(__DIR__ . '/../../../.credentials/gmail_client.json');
        $client->setAccessType('offline');

        $credentialsPath = $this->expandHomeDirectory(__DIR__ . '/../../../.credentials/gmail_token.json');
        if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
        } else {
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

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

        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }

    private function expandHomeDirectory($path)
    {
        $homeDirectory = getenv('HOME');
        if (empty($homeDirectory)) {
            $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
        }
        return str_replace('~', realpath($homeDirectory), $path);
    }
}

https://developers.google.com/gmail/api/quickstart/php.