使用 gmail 循环阅读正文 api

Loop to read the body with gmail api

我想在我的一个项目中实施 Gmail API。因此,我按照 google 的快速入门教程进行了操作,效果很好。

require "google/apis/gmail_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"

OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Gmail API Ruby Quickstart".freeze
CREDENTIALS_PATH = "credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_MODIFY

##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
  token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
  authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
  user_id = "default"
  credentials = authorizer.get_credentials user_id
  if credentials.nil?
    url = authorizer.get_authorization_url base_url: OOB_URI
    puts "Open the following URL in the browser and enter the " \
         "resulting code after authorization:\n" + url
    code = "XXXX"
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

messages = []
next_page = nil
begin
result = service.list_user_messages('me', max_results: [500].min, page_token: next_page)
messages += result.messages
break if messages.size >= 500
next_page = result.next_page_token
end while next_page

puts "Found #{messages.size} messages"

messages.each do |message| 
    puts "- #{message.thread_id }"
end

在项目中,我们用标签做了一个循环,一切正常。现在,我想对我的电子邮件做同样的事情。正如您在以下脚本中看到的,我正在循环邮件的 ID。这没有问题,但是当我尝试循环内容或文档中描述的任何其他 attributes 时,它会呈现一个空数组。

puts "- #{message.body }"

你有什么线索可以让我找出我的错误吗?

您可以使用

listing messages 试试这个 API

响应仅包含线程 ID 和消息 ID。

要检索 message.body,您需要使用方法 Users.messages: get 将您用 Users.messages: list 检索到的消息 ID 指定为参数。