# Yahoo! Mail bindings # ymail.rb # Richard Crowley # richarddcrowley.org # 4-2-2007 # See the Yahoo! Mail API at http://developer.yahoo.com/mail/ for the # details on the API calls wrapped up here require 'json' require 'net/http' class YMail @@creds = false # Our client is identified by an application ID, a web services session # ID and a Y cookie that must all be passed with each request def initialize(wssid, ycookie) unless @@creds @@creds = YAML::load_file("#{RAILS_ROOT}/config/ymail.yml") end @wssid = wssid @ycookie = ycookie end # Returns a hash of hashes full of interesting user info def get_user_data json_rpc('GetUserData') end # List all folders owned by this account # It turns out you can usually skip this call knowing you're looking # for "Inbox" or something equally descriptive def list_folders json_rpc('ListFolders') end # Get all the messages within a given folder def list_messages(folder = 'Inbox', sort = 'down', start = nil) json_rpc('ListMessages', [{'sortKey' => 'date', 'sortOrder' => sort, 'fid' => folder, 'startMid' => start, 'numMid' => 0, 'numInfo' => 20}]) end # Get a specific message def get_message(message, folder = 'Inbox') json_rpc('GetMessage', [{'fid' => folder, 'message' => [{'mid' => message}]}]); end protected # The main call used to access Yahoo! Mail # This would be easier with SOAP, but Ruby's SOAP doesn't support # sending cookies (as far as I can tell) def json_rpc(method, params = [{}]) j = JSON.generate({'method' => method.to_s, 'params' => params}) uri = URI.parse("http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc?appid=#{@@creds['application_id']}&WSSID=#{@wssid}") http = Net::HTTP.new(uri.host, Net::HTTP.http_default_port) j = JSON.parse(http.post(uri.request_uri, j, {'Content-Type' => 'application/json', 'Cookie' => "#{@ycookie};"}).body) return false if j['error'] j['result'] end end