Created
June 8, 2015 18:28
-
-
Save daviddavis/7de000748614b3d164f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'rubygems' | |
| require 'gmail' | |
| require 'terminal-notifier' | |
| require 'pry-byebug' | |
| GMAIL_USER = ENV['GMAIL_USER'] | |
| GMAIL_PASS = ENV['GMAIL_PASS'] | |
| STORE_FILE = "last_uid" | |
| INTERVAL = 15 # seconds | |
| def notify(message, title: "Mail Notification", subtitle: "") | |
| TerminalNotifier.notify(message, | |
| title: title, | |
| subtitle: subtitle, | |
| appIcon: "gmail.png", | |
| open: "http://www.gmail.com") | |
| end | |
| def format_address(addr) | |
| if addr.name.empty? | |
| "#{addr.name} <#{addr.mailbox}@#{addr.host}>" | |
| else | |
| "#{addr.mailbox}@#{addr.host}" | |
| end | |
| end | |
| def last_uid(uid = nil) | |
| if uid.nil? | |
| return 0 if !File.exists?(STORE_FILE) || File.size(STORE_FILE) == 0 | |
| File.open(STORE_FILE, "r") { |file| uid = file.read } | |
| uid = 0 if uid.empty? | |
| else | |
| File.open(STORE_FILE, "w+") { |file| file.write(uid.to_s) } | |
| end | |
| return uid.to_i | |
| end | |
| loop do | |
| Gmail.connect(GMAIL_USER, GMAIL_PASS) do |gmail| | |
| if gmail.logged_in? | |
| messages = gmail.inbox.emails(:unread).reject { |msg| msg.uid <= last_uid } | |
| message = messages.sort_by(&:uid).last | |
| if message | |
| from = format_address(message.from.first) | |
| subject = message.subject | |
| notify(subject, title: "You've received a new email", subtitle: "From: #{from}") | |
| last_uid(message.uid) | |
| end | |
| else | |
| notify("Failed to connect", title: "Could not log into Gmail") | |
| end | |
| end | |
| sleep(INTERVAL) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment