Ruby error: "get_tagged_response: Error in IMAP command received by server"

By Alvin J. Alexander, devdaily.com

If you ever see the following error message when running a Ruby script that uses the IMAP library it may not be as bad as it seems:

/usr/local/lib/ruby/1.8/net/imap.rb:971:in get_tagged_response: 
Error in IMAP command received by server. (Net::IMAP::NoResponseError) from /usr/local/lib/ruby/1.8/net/imap.rb:1022:in send_command from /usr/local/lib/ruby/1.8/monitor.rb:229:in synchronize from /usr/local/lib/ruby/1.8/net/imap.rb:1007:in send_command from /usr/local/lib/ruby/1.8/net/imap.rb:1140:in search_internal from /usr/local/lib/ruby/1.8/monitor.rb:229:in synchronize from /usr/local/lib/ruby/1.8/net/imap.rb:1136:in search_internal from /usr/local/lib/ruby/1.8/net/imap.rb:675:in search from read_but_no_reply.rb:11

This "in get_tagged_response: Error in IMAP command received by server" error message looks bad, but as a practical matter it usually means I have something wrong in my search criteria. For instance, the following code segment has a slight error:

# intentional error here
imap.search(["FROM",  "acme.com",
             "AFTER", "15-Nov-2006",
             "SEEN",
             "NOT",   "ANSWERED"]).each do |message_id|
  env = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  puts "#{env.from[0].name}: \t#{env.subject}"
end

The subtle error is that there is no AFTER keyword(!). I assumed that because there was a BEFORE keyword the opposite would be called AFTER, but no, the correct string is SINCE. Changing AFTER to SINCE fixes the problem, and gets rid of the ugly Error in IMAP command received by server error message.

This error is fixed in the following code:

# error fixed here
imap.search(["FROM",  "acme.com",
             "SINCE", "15-Nov-2006",
             "SEEN",
             "NOT",   "ANSWERED"]).each do |message_id|
  env = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  puts "#{env.from[0].name}: \t#{env.subject}"
end

So, when you see this message, take a close look at your IMAP search criteria.


devdaily logo