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