Hatena::Grouprubyist

たばさの RSSフィード

03/17(火) 2009

gmail inbox list表示

| gmail inbox list表示 - たばさの を含むブックマーク はてなブックマーク - gmail inbox list表示 - たばさの

gmail-check.rb

#!/usr/bin/env ruby
# 参考 http://blog.app2u.jp/index/ruby/ruby-gmail

require 'net/imap'
require 'nkf'
require'time'

class String
  def utf
    NKF::nkf('-u',self)
  end
  def sjis
    NKF::nkf('-s',self)
  end
end

id =''
pass =''


key =ARGV[0] || 'inbox' 
puts key

begin

  # GmailにIMAPで接続、ログインする
  @imap = Net::IMAP.new( 'imap.gmail.com', 993, true )
  @imap.login( id, pass ) # ID、パスワード
  @imap.examine( key )
  k =@imap.fetch(1..-1,'ENVELOPE')
  puts k.map{|i| a =Time.parse(i.attr["ENVELOPE"].date); [a.strftime("%Y-%m-%d %H:%M:%S"), i.attr["ENVELOPE"].subject.sjis,i.attr["ENVELOPE"].from[0].mailbox.sjis, "" ] }.sort.reverse

rescue

  p $! # 例外処理

ensure

  # 切断する
  @imap.logout
  @imap.disconnect
  # puts"(end)"

end
>gmail-check.rb
inbox
2009-03-16 13:17:23
SourceForge.JP: SF.JP キャリア開始/フォーラム,Wiki機能変更他
sf-admin

2009-01-23 02:01:20
SourceForge.JP サイト更新情報: AdSense を使用可能に、他
sf-admin



google:require 'net/imap'


2009/04/03 改良

gmail-check.rb

#!/usr/bin/env ruby
# http://rubyist.g.hatena.ne.jp/hatecha/
# cf. http://blog.app2u.jp/index/ruby/ruby-gmail
#     http://blog.tomatomax.net/archives/2355

require 'net/imap'
require 'nkf'
require 'pp'
require 'time'
require 'optparse'
opt = OptionParser.new
opt.on('-c') {|v| $checkonly=true }
opt.parse!(ARGV)

class String
  def m_utf
    NKF::nkf('-u -m0',self)
  end
  def m_sjis
    NKF::nkf('-s -m0',self)
  end
  def utf
    NKF::nkf('-u',self)
  end
  def sjis
    NKF::nkf('-s',self)
  end
end

class Net::IMAP::Envelope
  def fromStr
    s=self
    "#{(s.from[0].name||"").sjis} #{s.from[0].mailbox.sjis}@#{s.from[0].host.sjis}"
  end
end

class MyGmail
  attr_accessor :envelopes,:imap
  def initialize
    # GmailにIMAPで接続、ログインする
    port=993
    usessl=true
    @imap = Net::IMAP.new( 'imap.gmail.com', port, usessl )
  end
  def login(id=@id, pass=@pass)
    @id=id
    @pass=pass
    @imap.login( id, pass ) # ID、パスワード
  end
  def setkey key=@key
    @key=key
    @imap.examine( key )
  end
  def fetch max=20, min=1
    @mails=@imap.fetch(min..max,'ENVELOPE')
    @envelopes=@mails.map{|i|
      s= i.attr["ENVELOPE"]
      { :date, Time.parse(s.date).strftime("%Y-%m-%d %H:%M:%S"),
        :subject, s.subject.sjis,
        :from, s.fromStr,
        :messageNo, i.seqno,
        :message_id, s.message_id,
        :all, i
      }
    }
  end
  def check
    old=@envelopes
   # @imap.logout
    tmp=@key
    self.setkey "inbox"
    self.setkey tmp
    self.fetch
    if old != @envelopes
      printf "%+d\n",@envelopes.size - old.size
      @envelopes.each{|i|
        self.show i[:messageNo] if [] == old.select{|j| j[:message_id] ==i[:message_id]}
      }
    end
    @envelopes.size - old.size
  end
  def cd folder="inbox"
    puts folder
    folder="inbox" if folder.chomp=="~"
    self.setkey folder
    self.fetch
  end
  def show num=nil
    self.getNo num if num != nil
    if @mail
  # p @envelope,@envelope.class
      tmp= @envelope.attr["ENVELOPE"]
      puts "message_id: #{tmp.message_id}"
      puts "from: #{tmp.fromStr}"
      puts "subject: #{tmp.subject.sjis}"
      puts
      puts @body
    else
      self.list
    end
  end
  def list
    @envelopes.sort_by{|i|i[:date]}.reverse.each{|i|print "#{format"%2d",i[:messageNo]}:#{i[:date]} #{i[:subject]} /#{i[:from]}"; puts}
  end
  def detail num=nil
    self.getNo num if num != nil
    @envelope.each{|i| puts "#{i}".sjis}
    puts @header,@body
  end
  def getNo num
    @mail=@imap.fetch(num, "RFC822")[0].attr["RFC822"].sjis
    @envelope=@imap.fetch(num,'ENVELOPE')[0]
   # @envelope
    if @mail
      @mail=~/(.*)\r\n\r\n(.*)/m
      @header,@body=$1,$2
    end
    @body
  end
  def noop
    @imap.noop
  end
  def quit
    # 切断する
    @imap.logout
    @imap.disconnect
  end
end

def help
  puts 'help, $show, $getNo 3, $detail, $cd "inbox", $fetch [max, min], $check ... '
end

def start mygmail,mails,key
  mygmail=MyGmail.new
  mygmail.login $id,$pass
  mygmail.setkey key
  mails=mygmail.fetch
  [mygmail,mails]
end

class NilClass
  def name
    ""
  end
end

# gmail address と password
id=''
pass=''


key=ARGV[0] || 'inbox' 
puts key


mygmail=""
mails=""
mygmail,mails = start mygmail,mails,key

if $checkonly
  mygmail.show
  loop{
    print">"
    mygmail.check
    10.times{ 24.times{sleep 5; print"\r",Time.now }; mygmail.noop; }
  }
  exit
end


while 1
  begin
    print">"
    gets

    $_.sub!(/^\$/){"mygmail."}
    # help
    if $_=~/^help/
      help
    elsif $_=~/^reset/
      mygmail,mails = start mygmail,mails,key
    elsif $_=~/^$/
      $res=mygmail.noop
      mygmail.list
    # message No
    elsif $_.chomp=~/^\d+\z/
      mygmail.show $_.to_i
    # eval
    else
      #p $_
      res=eval($_)
      # puts res if not res
    end
    print"#{$res.name}"
  rescue
    p $! # 例外処理
  ensure
    # puts"(end)"
  end
end

gmail-check.rb -c」でループ:

  2分ごとにログアウト防止noop、20分ごとにメールチェック。

  新着があれば表示。

トラックバック - http://rubyist.g.hatena.ne.jp/hatecha/20090317
カレンダー
<< 2009/03 >>
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
archive Error : RSSが取得できませんでした。