more efficient git-cur-branch.sh
[cmccabe-bin] / snarf_gmail.rb
1 #!/usr/bin/env ruby
2
3 #
4 # snarf_gmail.rb
5 #
6 # Copies mail from a gmail account
7 # You need ruby 1.9 for this
8 # You need the password gem for this
9 #
10 # Problem: this appears to only download some mails (usually around 383 or
11 # so). One workaround is to run this multiple times. Still not sure if there
12 # is a better workaround.
13 #
14 # Colin McCabe
15 #
16
17 require 'net/pop'
18 require 'optparse'
19 require 'ostruct'
20 require 'password'
21
22 class MyOptions
23   def self.parse(args)
24     opts = OpenStruct.new
25
26     # Fill in $opts values
27     parser = OptionParser.new do |myparser|
28       myparser.banner = "Usage: #{ File.basename($0) } [opts]"
29       myparser.separator("Specific options:")
30       myparser.on("--username USERNAME", "-u",
31               "Email account to fetch. (example: \
32 RareCactus@gmail.com)") do |u|
33               opts.username = u
34       end
35       myparser.on("--dry-run", "-d",
36               "Dry run. State what would be done without actually \
37 doing it.") do |a|
38               opts.dry_run = true
39       end
40     end
41
42     parser.parse!(args)
43     raise "must give a username" unless opts.username
44     return opts
45   end
46 end
47
48 # MAIN
49 begin
50   $opts = MyOptions.parse(ARGV)
51 rescue Exception => msg
52   $stderr.print("#{msg}.\nType --help to see usage information.\n")
53   exit 1
54 end
55
56 puts "type password for #{$opts.username}"
57 password = gets
58 password.chomp!
59
60 Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
61 Net::POP3.start("pop.gmail.com", 995, $opts.username, password) do |pop|
62   #pop.reset()
63   mails = pop.mails
64   n_mails = pop.n_mails
65   puts "found #{n_mails} mails."
66   if ($opts.dry_run)
67     puts "successfully connected."
68     exit 0
69   end
70   count = 0
71   mails.each do |mail|
72     fname = mail.unique_id
73     #fname = sprintf("%08d", count)
74     File.open(fname, 'w+') do|f|
75       f.write mail.pop
76     end
77     count = count + 1
78     if ((count % 100) == 0)
79       count = 0
80       print "."
81       STDOUT.flush
82     end
83   end
84 end
85 puts "done."
86 exit 0