require 'rubygems' require 'open-uri' require 'icalendar' require 'date' require 'net/smtp' require 'erb' require 'yaml' ICAL_URL = "http://www.google.com/calendar/ical...path_to_your_ical_file" FROM_EMAIL = 'your_email_address@domain.com' MAIL_TEMPLATE_FILE = 'mail_template.html.erb' SENT_NOTIFICATIONS_FILE = 'sent_notifications.yml' GROUP_LIST_FILE = 'group_list.txt' DAYS_BEFORE_TO_SEND = 2 @logger = Logger.new('notification.log') @logger.datetime_format = "%Y-%m-%d %H:%M:%S " @logger.info 'Start' def init begin @logger.info ' Reading ical from google' myFile = open(ICAL_URL).read cals = Icalendar.parse(myFile) cal = cals.first cal.events.each{ |e| time_diff = e.dtstart - DateTime.now if time_diff < (DAYS_BEFORE_TO_SEND * 24 * 60 * 60) && time_diff > 0 @logger.info " Event: #{e.summary} in #{round_f((e.dtstart - DateTime.now).to_f)} days." if notified?(e.uid) @logger.info ' notification previousy sent.' else send_to = group_list msg = ERB.new(File.read( MAIL_TEMPLATE_FILE )).result( binding ) send_email('Notifications', FROM_EMAIL, send_to, e.summary, msg) @logger.info " sending Email {recipients: #{send_to.length}}" add_notification_to_list(e.uid) @logger.info " adding to notification list {uid:#{uid}}" end end } rescue @logger.error 'ERROR: ' + $!.message + ', ' + $!.backtrace.join("\n") end end def format_date(dt) dt.strftime('%a %b %d, %Y - %I:%M %p') end def round_f(num) (num * 100).round / 100.0 end def add_notification_to_list(uid) if File.exists?( SENT_NOTIFICATIONS_FILE ) y_content = YAML.load( File.open( SENT_NOTIFICATIONS_FILE ) ) end y_content = [] unless y_content.is_a?( Array ) File.open( SENT_NOTIFICATIONS_FILE, 'w+' ) { |yf| y_content.concat [ :date => Time.now, :uid => "#{uid}" ] YAML.dump( y_content, yf ) } end def notified?(uid) if File.exist?( SENT_NOTIFICATIONS_FILE ) File.open( SENT_NOTIFICATIONS_FILE ) { |yf| y_content = YAML.load( yf ) if y_content.is_a? Array y_content.each{ |e| return true if e[:uid] == uid } end } end return false #not found end def group_list begin IO.read( GROUP_LIST_FILE ).split(/\n/) rescue return Array['default_email@domain.com'] end end def send_email(from_alias, from, to_array, subject, message) msg = < To: #{to_array.collect{ |item| '<' + item + '>' }.join(',')} Subject: [NOTIFICATION]#{subject} Content-Type: text/html #{message} END_OF_MESSAGE Net::SMTP.start( 'mail.your.domain.com', 25 ) do |smtp| smtp.send_message msg, from, to_array end end init() @logger.info 'Stopped' @logger.close