Skip to content

Instantly share code, notes, and snippets.

@arkan
Forked from wkrsz/gist:1404434
Created March 17, 2012 17:07
Show Gist options
  • Save arkan/2062678 to your computer and use it in GitHub Desktop.
Save arkan/2062678 to your computer and use it in GitHub Desktop.
Retrieve Gmail Thread IDs
# Code example for http://wojt.eu/post/13496746332/retrieving-gmail-thread-ids-with-ruby
def patch_net_imap_response_parser(klass = Net::IMAP::ResponseParser)
klass.class_eval do
def msg_att
match(T_LPAR)
attr = {}
while true
token = lookahead
case token.symbol
when T_RPAR
shift_token
break
when T_SPACE
shift_token
token = lookahead
end
case token.value
when /\A(?:ENVELOPE)\z/ni
name, val = envelope_data
when /\A(?:FLAGS)\z/ni
name, val = flags_data
when /\A(?:INTERNALDATE)\z/ni
name, val = internaldate_data
when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
name, val = rfc822_text
when /\A(?:RFC822\.SIZE)\z/ni
name, val = rfc822_size
when /\A(?:BODY(?:STRUCTURE)?)\z/ni
name, val = body_data
when /\A(?:UID)\z/ni
name, val = uid_data
# Gmail extension additions.
# Cargo-Cult code warning: # I have no idea why the regexp - just copying a pattern
when /\A(?:X-GM-LABELS)\z/ni
name, val = flags_data
when /\A(?:X-GM-MSGID)\z/ni
name, vale = uid_data
when /\A(?:X-GM-THRID)\z/ni
name, val = uid_data
else
parse_error("unknown attribute `%s'", token.value)
end
attr[name] = val
end
return attr
end
end
end
def pull_thread_ids(login,password,days)
emails, thread_ids = nil
after_date = if days.to_i > 0
Date.today - days.to_i
else
nil
end
Gmail.new(login, password) do |gmail|
#let's not tamper with global Net::IMAP and patch singleton class instead...
patch_net_imap_response_parser gmail.imap.instance_variable_get("@parser").singleton_class
mailbox = gmail.mailbox("[Gmail]/All Mail")
query_filters = if after_date
{:after => after_date}
else
{}
end
emails = mailbox.emails query_filters
uids_range = emails.first.uid .. emails.last.uid
response_rows = gmail.imap.uid_fetch( uids_range, "(X-GM-THRID)")
thread_ids = response_rows.map {|row|
row.attr["X-GM-THRID"].to_s(16)
}
end
thread_ids
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment