Hướng dẫn how can i read gmail with gmail api in php? - Làm thế nào tôi có thể đọc gmail với gmail api trong php?

Đây là mã mẫu tôi đã sử dụng để phát triển một hệ thống bán vé email. Nó cho thấy cách lấy nhãn, tin nhắn và tiêu đề.

setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } 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);

    // Store the credentials to disk.
    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);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

/**
 * Get list of Messages in user's mailbox.
 *
 * @param  Google_Service_Gmail $service Authorized Gmail API instance.
 * @param  string $userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @return array Array of Messages.
 */
function listMessages($service, $userId, $optArr = []) {
  $pageToken = NULL;
  $messages = array();
  do {
    try {
      if ($pageToken) {
        $optArr['pageToken'] = $pageToken;
      }
      $messagesResponse = $service->users_messages->listUsersMessages($userId, $optArr);
      if ($messagesResponse->getMessages()) {
        $messages = array_merge($messages, $messagesResponse->getMessages());
        $pageToken = $messagesResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
    }
  } while ($pageToken);

  return $messages;
}

function getHeaderArr($dataArr) {
    $outArr = [];
    foreach ($dataArr as $key => $val) {
        $outArr[$val->name] = $val->value;
    }
    return $outArr;
}

function getBody($dataArr) {
    $outArr = [];
    foreach ($dataArr as $key => $val) {
        $outArr[] = base64url_decode($val->getBody()->getData());
        break; // we are only interested in $dataArr[0]. Because $dataArr[1] is in HTML.
    }
    return $outArr;
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

function getMessage($service, $userId, $messageId) {
  try {
    $message = $service->users_messages->get($userId, $messageId);
    print 'Message with ID: ' . $message->getId() . ' retrieved.' . "\n";

    return $message;
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
}

function listLabels($service, $userId, $optArr = []) {
    $results = $service->users_labels->listUsersLabels($userId);

    if (count($results->getLabels()) == 0) {
      print "No labels found.\n";
    } else {
      print "Labels:\n";
      foreach ($results->getLabels() as $label) {
        printf("- %s\n", $label->getName());
      }
    }
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
$user = 'me';

// Print the labels in the user's account.
listLabels($service, $user);

// Get the messages in the user's account.
$messages = listMessages($service, $user, [
    #'maxResults' => 20, // Return 20 messages.
    'labelIds' => 'INBOX', // Return messages in inbox.
]);

foreach ($messages as $message) {
    print 'Message with ID: ' . $message->getId() . "\n";

    $msgObj = getMessage($service, $user, $message->getId());

    $headerArr = getHeaderArr($msgObj->getPayload()->getHeaders());

    echo 'Message-ID: ' . $headerArr['Message-ID'];
    echo "\n";
    echo 'In-Reply-To: ' . (empty($headerArr['In-Reply-To']) ? '' : $headerArr['In-Reply-To']);
    echo "\n";
    echo 'References: ' . (empty($headerArr['References']) ? '': $headerArr['References']);
    echo "\n";

    #print_r($headerArr);

    $bodyArr = getBody($msgObj->getPayload()->getParts());
    echo 'Body: ' . (empty($bodyArr[0]) ? '' : $bodyArr[0]);
}

Reference:

https://developers.google.com/gmail/api/quickstart/php https://developers.google.com/gmail/api/v1/reference/users/messages/modify#php

Làm cách nào để đọc API hộp thư đến gmail?

Đăng nhập vào bảng điều khiển Google Cloud và tạo một dự án mới hoặc tiếp tục với một dự án hiện có ...
Tạo một dự án mới ..
Truy cập API và dịch vụ ..
Chuyển đến Bật API và Dịch vụ ..
Bật API Gmail ..
Định cấu hình màn hình đồng ý ..
Nhập tên ứng dụng ..
Chuyển đến thông tin đăng nhập ..
Tạo ID máy khách OAuth ..

Làm thế nào tôi có thể truy cập gmail trong PHP?

Cấu hình IMAP trong môi trường PHP và Gmail..
Cài đặt thư viện PHP IMAP.....
Bật tiện ích mở rộng thư viện IMAP trong tệp cấu hình PHP xóa dấu chấm phẩy (;) ở đầu dòng.....
Tăng giới hạn cho Chỉ thị MAX_EXECATION_TIME trong tệp php.ini ..
Khởi động lại Apache để làm cho những thay đổi này hiệu quả ..

Làm thế nào gửi API Gmail trong PHP?

Cách làm ứng dụng của bạn gửi email với API Gmail..
Bước 1: Tạo một dự án tại bảng điều khiển API của Google.....
Bước 2: Bật API Gmail.....
Bước 3: Thông tin xác thực và xác thực với OAuth 2.0.....
Bước 4: Chọn hướng dẫn nhanh.....
Bước 5: Thư viện máy khách API.....
Bước 6: Truy cập vào Gmail.....
Bước 7: Tạo email.....
Bước 8: Gửi email ..

Làm thế nào để bạn đọc email từ Gmail bằng API Gmail trong Python?

Python QuickStart..
Trên trang này..
Objectives..
Prerequisites..
Thiết lập môi trường của bạn.Bật API.Ủy quyền thông tin đăng nhập cho một ứng dụng máy tính để bàn ..
Cài đặt thư viện khách hàng Google ..
Định cấu hình mẫu ..
Chạy mẫu ..
Bước tiếp theo..