From a638d8f4e78a9e97dd5fc771963904047d8b647b Mon Sep 17 00:00:00 2001 From: Colin Patrick McCabe Date: Wed, 5 May 2010 06:34:29 -0700 Subject: [PATCH] snarf_mail: add --delete-after --- snarf_mail.rb | 65 +++++++++++++++++++++++++++++++++++++++++--------------- 1 files changed, 47 insertions(+), 18 deletions(-) diff --git a/snarf_mail.rb b/snarf_mail.rb index a2490b1..304c5ad 100755 --- a/snarf_mail.rb +++ b/snarf_mail.rb @@ -17,11 +17,16 @@ class MyOptions def self.parse(args) opts = OpenStruct.new opts.mailboxes = Array.new + opts.delete_after = false # Fill in $opts values parser = OptionParser.new do |myparser| myparser.banner = "Usage: #{ File.basename($0) } [opts]" myparser.separator("Specific options:") + myparser.on("--delete-after", "-d", + "Delete emails after fetching them.") do |d| + opts.delete_after = true + end myparser.on("--username USERNAME", "-u", "Email account to fetch. (example: \ RareCactus@gmail.com)") do |u| @@ -85,26 +90,50 @@ def format_uid(uid) end def snarf_mailbox(imap, mailbox) - imap.select(mailbox) - count = 0 - total_count = 0 - imap.search(["NOT", "DELETED"]).each do |message_id| - data = imap.fetch(message_id, [ "UID", "RFC822.HEADER", "RFC822.TEXT" ]) - a = data[0].attr - filename = "#{mailbox}#{format_uid(a["UID"])}" - fp = File.open(filename, 'w') - fp.write(a["RFC822.HEADER"]) - fp.write(a["RFC822.TEXT"]) - fp.close - count = count + 1 - total_count = total_count + 1 - if (count > 10) then - count = 0 - printf(".") - STDOUT.flush() + full_count = 0 + first_time = true + while true + count = 0 + msg_seqnos = Array.new + + imap.select(mailbox) + imap.search(["NOT", "DELETED"]).each do |message_id| + if (first_time == true) then + # Print a dot immediately after making first contact with the server. + # It is reassuring to the user. + printf(".") + STDOUT.flush() + first_time = false + end + data = imap.fetch(message_id, [ "UID", "RFC822.HEADER", "RFC822.TEXT" ]) + arr = data[0].attr + filename = "#{mailbox}#{format_uid(arr["UID"])}" + fp = File.open(filename, 'w') + fp.write(arr["RFC822.HEADER"]) + fp.write(arr["RFC822.TEXT"]) + fp.close + count = count + 1 + full_count = full_count + 1 + msg_seqnos << data[0].seqno.to_i + break if (count > 20) + end + if (count == 0) then + action_str = ($opts.delete_after == true) ? + "fetched and deleted" : "fetched" + puts "#{action_str} #{full_count} messages from #{mailbox}" + return + end + + # Print out a dot to signify progress + printf(".") + STDOUT.flush() + + # Delete messages if we're supposed to + if ($opts.delete_after == true) then + imap.store(msg_seqnos, "+FLAGS", [:Deleted]) + imap.expunge end end - puts "fetched #{total_count} messages from #{mailbox}" end # MAIN -- 1.6.6.rc1.39.g9a42