require 'rubygems' require 'net/imap' require 'tmail' require 'parsedate' # NOTE: Set these values before you run the script # Your gmail username. Just the username; don't include the '@gmail.com' part. USERNAME = "username" # Your gmail password PASSWORD = "password" # Set this to true if you want a system beep to signal a new message in the inbox. Set it to false if not. BEEP = true # This is the interval in minutes between inbox checks INTERVAL = 2 class GmailCheck def initialize(username, password, interval=5, beep=true) @beep = beep @username, @password = username, password @interval = interval * 60 @seen_ids = [] end def run loop do check_inbox @username, @password @update_loop ||= true sleep @interval end end def fetch_email(imap, message_id) begin email = imap.uid_fetch(message_id, "RFC822")[0].attr["RFC822"] rescue puts "Error fetching message #{message_id}. Skipping" nil end end def check_inbox(username, password) imap = Net::IMAP.new('imap.gmail.com', 993, true) imap.login(username, password) imap.select('INBOX') imap.uid_search(["ALL"])[-5,5].each do |message_id| if @seen_ids.include? message_id next else @seen_ids << message_id end email = fetch_email(imap, message_id) next if email.nil? # beep if @update_loop && @beep print 7.chr end x = TMail::Mail.parse(email) puts "time: #{x.date.strftime("%I:%M %p %a %b %d")}" puts "from: #{x.from}" puts "subject: #{x.subject}" puts end imap.close imap.disconnect end end if __FILE__ == $0 gmailcheck = GmailCheck.new(USERNAME, PASSWORD, INTERVAL, BEEP) gmailcheck.run end