How to delete specific mail on server by ruby/mikel mail?

2k views Asked by At

I want to use Ruby/Mikel Mail gem to access pop3, but am stuck finding a way to SELECTIVELY delete mails from the server. Here's some disfunctional example code which examplifies how I misunderstand the rdoc specs provided.

require 'rubygems'
require 'mail'

Mail.defaults do
  retriever_method :pop3, { :address => '...',                        
                     :user_name  => '...',
                     :password   => '...' }                        
end


puts "#{Mail.all.length} messages on server found."
if Mail.all.length > 0 
  mm = Mail.first
  puts mm.from
  puts "I delete all but the first mail!"

  mm.mark_for_delete = false
  Mail.find_and_delete

  puts "#{Mail.all.length} messages on server found."  
end

The result is that with 2 mails on the server, this script just deletes both. Instead I only want it to delete the first.

2

There are 2 answers

0
Felix Ogg On BEST ANSWER

Found it myself, answer for you if you are looking at same problem..

Turns out you have to throw a Block at find_and_delete(), to explicitly decide to skip deletion of messages, simply:

Mail.find_and_delete({:what=>:first}) { |msg| 
     msg.skip_deletion if msg.subject == "test1826"
}
0
kodywilson On

I know this post is ancient, but I actually had to use this gem recently and if anyone out there happens to need a way to delete email with a bit more granularity than just "first" or "last" with a count (like say all email older than a month), here is one way to do it:

s_keys = ['SENTBEFORE', (Time.now - (30 * 86_400)).strftime('%d-%b-%Y')]
Mail.find_and_delete(keys: s_keys) do |email, _imap, uid|
    puts 'Delete: ' + uid.to_s + '   ' + email.subject + '   ' + email.date.to_s
end