2012-04-23 55 views
4

我有關於Ruby 1.9.3一些腳本:如何在Ruby中使用net/imap在郵箱中搜索郵件?

require "net/imap" 
imap = Net::IMAP.new(mail_imap_server) 
imap.login(mail_login, mail_password) 
imap.select("INBOX") 
puts imap.search(["FROM", "[email protected]"]) 
imap.logout 
imap.disconnect 

如果所需的信息存在,那麼一切都很好。 如果所需的信息丟失,錯誤:

/opt/local/lib/ruby1.9/1.9.1/net/imap.rb:1332:in `block in search_internal': undefined method `[]' for nil:NilClass (NoMethodError) 
from /opt/local/lib/ruby1.9/1.9.1/monitor.rb:211:in `mon_synchronize' 
from /opt/local/lib/ruby1.9/1.9.1/net/imap.rb:1326:in `search_internal' 
from /opt/local/lib/ruby1.9/1.9.1/net/imap.rb:752:in `search' 
from ./mail.rb:12:in `mail' 
from ./mail.rb:26:in `<main>' 

我怎樣才能解決這個問題?

回答

1

首先檢查是否有結果的消息,使用救援,以防萬一

require "net/imap" 
imap = Net::IMAP.new(mail_imap_server) 
imap.login(mail_login, mail_password) 
imap.select("INBOX") 
begin 
    messages = imap.search(["FROM", "[email protected]"]) 
    puts messages if messages.length > 0 
rescue 
    puts "Error while retrieving the message" 
end 
imap.logout 
imap.disconnect 
+0

大感謝名單,彼得!這是工作。 – 2012-04-23 12:53:47

相關問題