循环以使用 gmail API 读取正文



我想在我的一个项目中实现Gmail API。所以我按照谷歌的快速入门教程女仆来做这件事,它工作得很好。

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。这可以正常工作,但是当我尝试循环文档中描述的内容或任何其他属性时,它会将数组渲染为空。

puts "- #{message.body }"

你有什么线索可以让我识别我的错误吗?

您可以使用试用此 API 来重现列出以下消息

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

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

最新更新