Skip to content

Instantly share code, notes, and snippets.

@obihann
Forked from danchoi/barebones gmail notifier
Created May 30, 2016 18:30
Show Gist options
  • Save obihann/7436e25aa1902092bed22fbb6641d1aa to your computer and use it in GitHub Desktop.
Save obihann/7436e25aa1902092bed22fbb6641d1aa to your computer and use it in GitHub Desktop.
A lightweight command-line Gmail notifier. Fill in your gmail username and password and run the script from the command line. It polls your gmail account and shows the latest messages in a terminal window.
require 'rubygems'
require 'net/imap'
require 'tmail'
require 'parsedate'
# NOTE: Set these values before you run the script
# Your gmail username
USERNAME = "YOUR_USERNAME"
# Your gmail password
PASSWORD = "YOUR_PASSWORD"
# Set this to true if you want a system beep to signal a new message in the inbox
BEEP = true
# This is the interval in minutes between inbox checks
INTERVAL = 1
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.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.search(["ALL"])[-5,5].each do |message_id|
next if @seen_ids.include? message_id
# beep
if @update_loop && @beep
print 7.chr
end
@seen_ids << message_id
email = fetch_email(imap, message_id)
next if email.nil?
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 "excerpt: #{x.body.split(/\s+/)[0,10].join(' ')}"
puts
end
rescue Exception => ex
puts "Error: #{ex.message}"
ensure
if imap
imap.close
imap.disconnect
end
end
end
if __FILE__ == $0
gmailcheck = GmailCheck.new(USERNAME, PASSWORD, INTERVAL, BEEP)
gmailcheck.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment