代码之家  ›  专栏  ›  技术社区  ›  Antoine Nedelec

在Symfony4中使用gmailapi

  •  0
  • Antoine Nedelec  · 技术社区  · 6 年前

    在我的symfony4网站上。目标是通过cron定期执行一个命令,该命令将获取所有未读电子邮件,获取内容,并处理一些内容,然后将其标记为已读。

    the official documentation ):

    • 通过composer安装了库
    • symfony的工作命令(应用程序:从未读邮件上传),使用此代码:

      $client = new \Google_Client();
      $client->setApplicationName('Gmail API PHP Quickstart');
      $client->addScope(\Google_Service_Gmail::GMAIL_READONLY);
      $client->setAuthConfig('credentials.json');
      $client->setAccessType('offline');
      $client->setPrompt('select_account consent');
      
      $gmail = new \Google_Service_Gmail($client);
      $list = $gmail->users_messages->listUsersMessages('me', ['maxResults' => 1000]);
      
      while ($list->getMessages() != null) {
          foreach ($list->getMessages() as $mlist) {
      
              $message_id = $mlist->id;
              var_dump($message_id);
      
          }
      
          if ($list->getNextPageToken() != null) {
              $pageToken = $list->getNextPageToken();
              $list = $gmail->users_messages->listUsersMessages('me', ['pageToken' => $pageToken, 'maxResults' => 1000]);
          } else {
              break;
          }
      } 
      

    我的身份验证是否正确?我应该把我的 在symfony?

    1 回复  |  直到 6 年前
        1
  •  2
  •   yaroslavche    6 年前

    我应该把我的凭证.json在symfony?

    我想最好的地方是 config public

    假设这个文件的路径是 config/gmail/credentials.json . 所以下一步是在命令中获取文件路径。为了这个你需要 kernel.project_dir kernel.project\u目录 /config/gmail/credentials.json

    要在命令中使用服务容器,您需要:

    • ContainerAwareInterface
    • ContainerAwareTrait $container 财产和 setContainer
    • 类型提示 ContainerInterface $container 指挥官,呼叫 parent::__construct setContainer($container)

    -

    // ...
    use Symfony\Component\DependencyInjection\ContainerAwareInterface;
    use Symfony\Component\DependencyInjection\ContainerAwareTrait;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class UploadFromUnreadEmailsCommand extends Command implements ContainerAwareInterface
    {
        use ContainerAwareTrait;
    
        public function __construct(ContainerInterface $container)
        {
            parent::__construct();
            $this->setContainer($container);
        }
    
        // ...
    
    }
    

    您链接的文档中还有getClient函数的示例。只需进行一些修改即可:

    private function getClient()
    {
        $projectDir = $this->container->getParameter('kernel.project_dir');
        $credentialsFilePath = sprintf('%s/config/gmail/credentials.json', $projectDir);
        $tokenFilePath = sprintf('%s/config/gmail/token.json', $projectDir);
    
        // ...
    }
    

    execute

    $client = $this->getClient();
    $gmail = new \Google_Service_Gmail($client);
    

    执行命令并遵循指令(生成令牌)。

    完整命令类:

    <?php
    
    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use Symfony\Component\Console\Style\SymfonyStyle;
    use Symfony\Component\DependencyInjection\ContainerAwareInterface;
    use Symfony\Component\DependencyInjection\ContainerAwareTrait;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class UploadFromUnreadEmailsCommand extends Command implements ContainerAwareInterface
    {
    
        use ContainerAwareTrait;
    
        protected static $defaultName = 'app:upload-from-unread-emails';
    
        /**
        * UploadFromUnreadEmailsCommand constructor.
        * @param $container
        */
        public function __construct(ContainerInterface $container)
        {
            parent::__construct();
            $this->setContainer($container);
        }
    
        protected function configure()
        {
            $this
                ->setDescription('Add a short description for your command')
            ;
        }
    
        private function getClient()
        {
            $projectDir = $this->container->getParameter('kernel.project_dir');
            $credentialsFilePath = sprintf('%s/config/gmail/credentials.json', $projectDir);
            $tokenFilePath = sprintf('%s/config/gmail/token.json', $projectDir);
    
            $client = new \Google_Client();
            $client->setApplicationName('Gmail API PHP Quickstart');
            $client->setScopes(\Google_Service_Gmail::GMAIL_READONLY);
            $client->setAuthConfig($credentialsFilePath);
            $client->setAccessType('offline');
            $client->setPrompt('select_account consent');
    
            // Load previously authorized token from a file, if it exists.
            if (file_exists($tokenFilePath)) {
                $accessToken = json_decode(file_get_contents($tokenFilePath), true);
                $client->setAccessToken($accessToken);
            }
    
            // If there is no previous token or it's expired.
            if ($client->isAccessTokenExpired()) {
                // Refresh the token if possible, else fetch a new one.
                if ($client->getRefreshToken()) {
                    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                } 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->fetchAccessTokenWithAuthCode($authCode);
                    $client->setAccessToken($accessToken);
    
                    // Check to see if there was an error.
                    if (array_key_exists('error', $accessToken)) {
                        throw new Exception(join(', ', $accessToken));
                    }
                }
                // Save the token to a file.
                if (!file_exists(dirname($tokenFilePath))) {
                    mkdir(dirname($tokenFilePath), 0700, true);
                }
                file_put_contents($tokenFilePath, json_encode($client->getAccessToken()));
            }
            return $client;
        }
    
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $io = new SymfonyStyle($input, $output);
    
            $client = $this->getClient();
    
            $gmail = new \Google_Service_Gmail($client);
            $list = $gmail->users_messages->listUsersMessages('me', ['maxResults' => 10]);
    
            while ($list->getMessages() != null) {
                foreach ($list->getMessages() as $mlist) {
    
                    $message_id = $mlist->id;
                    $io->text($message_id);
    
                }
    
                if ($list->getNextPageToken() != null) {
                    $pageToken = $list->getNextPageToken();
                    $list = $gmail->users_messages->listUsersMessages('me', ['pageToken' => $pageToken, 'maxResults' => 1000]);
                } else {
                    break;
                }
            }
    
            $io->success('Success');
        }
    }
    

    getClient 函数,其中get container parameter,init \Google_Service_Gmail

    # /src/Command/UploadFromUnreadEmailsCommand.php
    private $gmailService;
    public function __construct(GmailService $gmailService)
    {
        $this->gmailService = $gmailService;
    }