網(wǎng)上很多用pop3收郵件的例子,但是用pop3收郵件只能獲取收件箱里面所有郵件,郵件是否已讀等標記無法獲取,使用imap協(xié)議則避免了這個尷尬,imap不僅能獲得一個郵件的詳細信息(比如是否已讀,是否回復),它還允許用戶更改郵件的標記,但是目前支持imap協(xié)議的郵件服務器并不多,我知道的只有21cn和gmail,下面的例子中使用了代理 、SSL認證多個內(nèi)容,請大家參考。
imap郵件,都是按需索取,也就是說,當你得到一個Message的對象時,其實里面什么信息都沒有,當你在這個對象里用get方法取得信息時,比如getSubject,那么Message對象會重新訪問郵件服務器來得到這個消息的 ,所以在得到所有所需信息之前,不可以關閉目錄,更不可以斷開連接。
如果實在想在關閉目錄或者連接后操作Message對象的話,需要使用Folder對象的fetch方法得到所需信息。
這是一種介于pull和Persistent TCP/IP之間的技術:long polling(長輪詢)。原理是客戶端每次對服務的請求都被服務端hold住,等到有message返回或time out之后,會再次主動發(fā)起請求,等待message的到達。這種模式不需要保持心跳,也不需要持續(xù)TCP的占用,比較適合頁面端及時消息的推送。
SERVER = 'EMAILSERVICE'
USERNAME = 'USERNAME'
PW = 'PASSWORD'
require 'net/imap'
# Extend support for idle command. See online.
# http://www.ruby-forum.com/topic/50828
# https://gist.github.com/jem/2783772
# but that was wrong. see /opt/ruby-1.9.1-p243/lib/net/imap.rb.
class Net::IMAP
def idle
cmd = "IDLE"
synchronize do
@idle_tag = generate_tag
put_string(@idle_tag + " " + cmd)
put_string(CRLF)
end
end
def say_done
cmd = "DONE"
synchronize do
put_string(cmd)
put_string(CRLF)
end
end
def await_done_confirmation
synchronize do
get_tagged_response(@idle_tag, nil)
puts 'just got confirmation'
end
end
end
class Remailer
attr_reader :imap
public
def initialize
@imap = nil
@mailer = nil
start_imap
end
def tidy
stop_imap
end
def print_pust
envelope = @imap.fetch(-1, "ENVELOPE")[0].attr["ENVELOPE"]
puts "From:#{envelope.from[0].name}\t Subject: #{envelope.subject}"
end
def bounce_idle
# Bounces the idle command.
@imap.say_done
@imap.await_done_confirmation
# Do a manual check, just in case things aren't working properly.
@imap.idle
end
private
def start_imap
@imap = Net::IMAP.new('pop.i-click.com')
@imap.login USERNAME, PW
@imap.select 'INBOX'
# Add handler.
@imap.add_response_handler do |resp|
if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
@imap.say_done
Thread.new do
@imap.await_done_confirmation
print_pust
@imap.idle
end
end
end
@imap.idle
end
def stop_imap
@imap.done
end
end
begin
Net::IMAP.debug = true
r = Remailer.new
loop do
puts 'bouncing...'
r.bounce_idle
sleep 15*60
#一般設置15分鐘無操作保持長鏈接
end
ensure
r.tidy
end