Created
April 21, 2010 05:25
This file contains 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
#!/usr/bin/env ruby | |
require 'optparse' | |
require 'rest_client' | |
require 'open-uri' | |
CLIENT_LOGIN_URI = URI.parse('https://www.google.com/accounts/ClientLogin') | |
CLIENT_LOGIN_HEADERS = {'Content-type' => 'application/x-www-form-urlencoded'} | |
SERVICE = 'mail' | |
ACCOUNT_TYPE = 'GOOGLE' | |
SOURCE = 'myaname-myprogram-0.0.1' | |
DOMAIN = 'gmail.com' | |
def get_auth_token(email, password, logintoken=nil, logincaptcha=nil) | |
params = { | |
:accountType => ACCOUNT_TYPE, | |
:Email => email, | |
:Passwd => password, | |
:service => SERVICE, | |
:source => SOURCE, | |
:logintoken => logintoken, | |
:logincaptcha => logincaptcha | |
} | |
resp = RestClient.post(CLIENT_LOGIN_URI.to_s, params, CLIENT_LOGIN_HEADERS) | |
lines = resp.body.split("\n") | |
auth_line = lines.find {|l| l =~ /^Auth=.*/i} | |
auth_line.sub(/^Auth=/i, '') | |
end | |
def setting_uri(domain, username, setting_id) | |
URI.parse("https://apps-apis.google.com/a/feeds/emailsettings/2.0/#{domain}/#{username}/#{setting_id}") | |
end | |
def forwarding_uri(domain, username) | |
setting_uri(domain, username, 'forwarding') | |
end | |
def forwarding_xml(forward_to, action="ARCHIVE") | |
return <<-XML | |
<?xml version="1.0" encoding="utf-8"?> | |
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006"> | |
<apps:property name="enable" value="true" /> | |
<apps:property name="forwardTo" value="#{forward_to}" /> | |
<apps:property name="action" value="#{action}" /> | |
</atom:entry> | |
XML | |
end | |
def settings_request_headers(auth_token) | |
{ | |
'Content-type' => 'application/atom+xml', | |
'Authorization' => "GoogleLogin auth=#{auth_token}" | |
} | |
end | |
def strip_username(email) | |
email.split('@').first | |
end | |
# ... optparse junk to set everything in @options ... | |
token = get_auth_token(@options[:email], @options[:password]) | |
headers = settings_request_headers(token) | |
xml = forwarding_xml(@options[:forward_to]) | |
# I presume the username has to be your email address without the @gmail.com | |
uri = forwarding_uri(DOMAIN, strip_username(@options[:email])) | |
# Raises RestClient::Unauthorized (401) | |
resp = RestClient.put(uri.to_s, xml, headers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment