Advertisement
Guest User

Untitled

a guest
May 30th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. require 'rubygems'
  2. require 'net/imap'
  3. require 'tmail'
  4. require 'parsedate'
  5.  
  6. # NOTE: Set these values before you run the script
  7.  
  8. # Your gmail username
  9. USERNAME = "YOUR_USERNAME"
  10. # Your gmail password
  11. PASSWORD = "YOUR_PASSWORD"
  12. # Set this to true if you want a system beep to signal a new message in the inbox
  13. BEEP = true
  14. # This is the interval in minutes between inbox checks
  15. INTERVAL = 1
  16.  
  17. class GmailCheck
  18.  
  19. def initialize(username, password, interval=5, beep=true)
  20. @beep = beep
  21. @username, @password = username, password
  22. @interval = interval * 60
  23. @seen_ids = []
  24. end
  25.  
  26. def run
  27. loop do
  28. check_inbox @username, @password
  29. @update_loop ||= true
  30. sleep @interval
  31. end
  32. end
  33.  
  34. def fetch_email(imap, message_id)
  35. begin
  36. email = imap.fetch(message_id, "RFC822")[0].attr["RFC822"]
  37. rescue
  38. puts "Error fetching message #{message_id}. Skipping"
  39. nil
  40. end
  41. end
  42.  
  43. def check_inbox(username, password)
  44. imap = Net::IMAP.new('imap.gmail.com', 993, true)
  45.  
  46. imap.login(username, password)
  47.  
  48. imap.select('INBOX')
  49.  
  50. imap.search(["ALL"])[-5,5].each do |message_id|
  51.  
  52. next if @seen_ids.include? message_id
  53. # beep
  54. if @update_loop && @beep
  55. print 7.chr
  56. end
  57. @seen_ids << message_id
  58.  
  59. email = fetch_email(imap, message_id)
  60. next if email.nil?
  61. x = TMail::Mail.parse(email)
  62. puts "time: #{x.date.strftime("%I:%M %p %a %b %d")}"
  63. puts "from: #{x.from}"
  64. puts "subject: #{x.subject}"
  65. puts "excerpt: #{x.body.split(/\s+/)[0,10].join(' ')}"
  66. puts
  67. end
  68.  
  69. rescue Exception => ex
  70. puts "Error: #{ex.message}"
  71. ensure
  72. if imap
  73. imap.close
  74. imap.disconnect
  75. end
  76. end
  77. end
  78.  
  79. if __FILE__ == $0
  80. gmailcheck = GmailCheck.new(USERNAME, PASSWORD, INTERVAL, BEEP)
  81. gmailcheck.run
  82. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement