-
-
Save kivanio/7be59ebb389d975def9fa5b7262d4319 to your computer and use it in GitHub Desktop.
June 2014 Gmail API list emails with PDF attachements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright (C) 2012 Google Inc. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
require 'rubygems' | |
require 'google/api_client' | |
require 'google/api_client/client_secrets' | |
require 'google/api_client/auth/file_storage' | |
require 'google/api_client/auth/installed_app' | |
require 'logger' | |
require 'ostruct' | |
require 'json' | |
API_VERSION = 'v1' | |
CACHED_API_FILE = "gmail-#{API_VERSION}.cache" | |
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json" | |
# Handles authentication and loading of the API. | |
def setup() | |
log_file = File.open('gmail.log', 'a+') | |
log_file.sync = true | |
logger = Logger.new(log_file) | |
logger.level = Logger::DEBUG | |
client = Google::APIClient.new(:application_name => 'Ruby Drive sample', | |
:application_version => '1.0.0') | |
# FileStorage stores auth credentials in a file, so they survive multiple runs | |
# of the application. This avoids prompting the user for authorization every | |
# time the access token expires, by remembering the refresh token. | |
# Note: FileStorage is not suitable for multi-user applications. | |
file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE) | |
if file_storage.authorization.nil? | |
client_secrets = Google::APIClient::ClientSecrets.load | |
# The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed | |
# application flow, which ties in with FileStorage to store credentials | |
# between runs. | |
flow = Google::APIClient::InstalledAppFlow.new( | |
:client_id => client_secrets.client_id, | |
:client_secret => client_secrets.client_secret, | |
:scope => ['https://www.googleapis.com/auth/gmail.readonly'] | |
) | |
client.authorization = flow.authorize(file_storage) | |
else | |
client.authorization = file_storage.authorization | |
end | |
gmail = nil | |
# Load cached discovered API, if it exists. This prevents retrieving the | |
# discovery document on every run, saving a round-trip to API servers. | |
if File.exists? CACHED_API_FILE | |
File.open(CACHED_API_FILE) do |file| | |
gmail = Marshal.load(file) | |
end | |
else | |
gmail = client.discovered_api('gmail', API_VERSION) | |
File.open(CACHED_API_FILE, 'w') do |file| | |
Marshal.dump(gmail, file) | |
end | |
end | |
return client, gmail | |
end | |
def list_messages(client, gmail) | |
@emails = client.execute( | |
api_method: gmail.users.messages.list, | |
parameters: { | |
q: "filename:pdf", | |
maxResults: 10, | |
userId: "me"}, | |
headers: {'Content-Type' => 'application/json'} | |
) | |
end | |
def show_message(client, gmail, emails) | |
email_hash = emails.data.messages[0].to_hash | |
email = OpenStruct.new(email_hash) | |
# email.id | |
e = client.execute( | |
api_method: gmail.users.messages.get, | |
parameters: { | |
id: email.id, | |
userId: "me"}, | |
headers: {'Content-Type' => 'application/json'} | |
) | |
# email.attachment_id = "folley" | |
# return email | |
return e | |
# hash = { "country" => "Australia", :population => 20_000_000 } | |
# data = OpenStruct.new(hash) | |
end | |
def get_attachment(client, gmail, email) | |
email_hash = emails.data.messages[0].to_hash | |
email = OpenStruct.new(email_hash) | |
email.id | |
e = client.execute( | |
api_method: gmail.users.attachments.get, | |
parameters: { | |
messageId: email.id, | |
userId: "me"}, | |
headers: {'Content-Type' => 'application/json'} | |
) | |
# hash = { "country" => "Australia", :population => 20_000_000 } | |
# data = OpenStruct.new(hash) | |
end | |
client, gmail = setup() | |
@emails = list_messages(client, gmail) | |
count = @emails.data.messages.count | |
puts "you have #{count} attachements " | |
# Pretty print the API result | |
jj @emails.data.messages | |
puts "you have #{count} attachments " | |
@email = show_message(client, gmail, @emails) | |
one = @email.data | |
jj one | |
puts "#######" | |
my_hash = one.to_hash | |
puts my_hash | |
puts "#######" | |
my_os = OpenStruct.new(my_hash) | |
payload = OpenStruct.new(my_os.payload) | |
# parts = OpenStruct.new(my_os.payload['parts']) | |
puts my_os.payload.length | |
puts my_os.payload['parts'] | |
puts "------------" | |
puts "parts length #{my_os.payload['parts'][1]['parts'].length}" | |
puts my_os.payload['parts'][1]['parts'][1]['body']['attachmentId'] | |
# parts = OpenStruct.new(my_os.payload['parts']) | |
# puts my_os | |
# puts @email | |
puts "******************" | |
# @attachment = get_attachment(client, gmail, @emails) | |
# jj @attachment.data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright (C) 2012 Google Inc. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
require 'rubygems' | |
require 'google/api_client' | |
require 'google/api_client/client_secrets' | |
require 'google/api_client/auth/file_storage' | |
require 'google/api_client/auth/installed_app' | |
require 'logger' | |
API_VERSION = 'v1' | |
CACHED_API_FILE = "gmail-#{API_VERSION}.cache" | |
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json" | |
# Handles authentication and loading of the API. | |
def setup() | |
log_file = File.open('gmail.log', 'a+') | |
log_file.sync = true | |
logger = Logger.new(log_file) | |
logger.level = Logger::DEBUG | |
client = Google::APIClient.new(:application_name => 'Ruby Drive sample', | |
:application_version => '1.0.0') | |
# FileStorage stores auth credentials in a file, so they survive multiple runs | |
# of the application. This avoids prompting the user for authorization every | |
# time the access token expires, by remembering the refresh token. | |
# Note: FileStorage is not suitable for multi-user applications. | |
file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE) | |
if file_storage.authorization.nil? | |
client_secrets = Google::APIClient::ClientSecrets.load | |
# The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed | |
# application flow, which ties in with FileStorage to store credentials | |
# between runs. | |
flow = Google::APIClient::InstalledAppFlow.new( | |
:client_id => client_secrets.client_id, | |
:client_secret => client_secrets.client_secret, | |
:scope => ['https://www.googleapis.com/auth/gmail.readonly'] | |
) | |
client.authorization = flow.authorize(file_storage) | |
else | |
client.authorization = file_storage.authorization | |
end | |
gmail = nil | |
# Load cached discovered API, if it exists. This prevents retrieving the | |
# discovery document on every run, saving a round-trip to API servers. | |
if File.exists? CACHED_API_FILE | |
File.open(CACHED_API_FILE) do |file| | |
gmail = Marshal.load(file) | |
end | |
else | |
gmail = client.discovered_api('gmail', API_VERSION) | |
File.open(CACHED_API_FILE, 'w') do |file| | |
Marshal.dump(gmail, file) | |
end | |
end | |
return client, gmail | |
end | |
def list_messages(client, gmail) | |
@emails = client.execute( | |
api_method: gmail.users.messages.list, | |
parameters: { | |
userId: "me"}, | |
headers: {'Content-Type' => 'application/json'} | |
) | |
end | |
client, gmail = setup() | |
@emails = list_messages(client, gmail) | |
count = @emails.data.messages.count | |
puts "you have #{count} attachements " | |
# Pretty print the API result | |
jj @emails.data.messages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment