Saturday, February 20, 2010

fetch Gmail with ruby

  • net/pop(POP3)かnet/imap(IMAP)を使う
  • POP3はruby187でも192でも動くけど、全てのメールをフェッチするのでgmailには適さない
  • IMAPはメールクライアントのような機能を持っているので、未読メールだけ取得するなどのことができる
  • しかしなぜかruby19では動かなかった
  • またいずれでも取得メールをutf8でencodeするときruby19のString#encodeが効かなかったのでKconvをrequireする必要があった

#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
require "net/imap"
require "kconv"
require "rubygems"
require "termcolor"

class Gmail
  def initialize(username, password)
    begin
      @imap = Net::IMAP.new('imap.gmail.com', 993, true)
      @imap.login(username, password)
    rescue Exception => e
      puts e
    end
  end

  def fetch(select="INBOX", ids="UNSEEN")
    begin
      @imap.examine(select)
      ids = @imap.search(ids)
      @imap.fetch(ids, "ENVELOPE").each_with_index do |mail, i|
        sender = mail.attr["ENVELOPE"].sender[0]
        name = sender.name || sender.mailbox || sender.host
        subject = mail.attr["ENVELOPE"].subject || "(no subject)"
        puts TermColor.colorize("#{i+1}:", "red") +
             TermColor.colorize("#{name.toutf8} : ", 'green') +
             TermColor.colorize("#{subject.toutf8}", 'yellow')
      end
    rescue Exception => e
      puts e
    ensure
      @imap.disconnect
    end
  end
end

g = Gmail.new()
g.fetch

# -*- encoding:utf-8 -*-
require "net/pop"
require "kconv"

username = ''
password = ''
address  = 'pop.gmail.com'
port     = 995

Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
Net::POP3.start(address, port, username, password) do |pop|
  if pop.mails.empty?
    $stderr.puts 'no mail.'
  else
    puts pop.mails[-1].pop.toutf8
    # pop.mails.each do |m|
    #   puts m.pop
    # end
    #puts "#{pop.mails.length} mails received."
  end
end

No comments: