Sending Gmail calendar events in Rails 4

Here I am telling about how to send gmail calendar events to user emails. I am using Rails 4.2 and Ruby 2.2.1

For this we can use the best available code package the ‘icalnder’ gem.

Icalender Github

In Gemfile add:

gem 'icalendar'

Suppose we are using user_mailer.rb for sending emails in this case. And we are sending emails to manager and a participant when a conversation is scheduled between them.

I created a method as below.

in user_mailer.rb

   def conversation_scheduled(conversation_id, opts={})
      @conversation = Conversation.find_by_id(conversation_id)
      @manager = @conversation.try(:manager)
      @participant = @conversation.try(:participant)
      @base_url = opts['base_url']

      if opts[:send_to] == 'manager'
        cal = calender_event(@conversation, @manager, "Conversation is scheduled with #{@participant.full_name}", "You have scheduled a conversation with Mr/Mrs #{@participant.full_name} on #{@conversation.starting_time}")  
        attachments['conversation_sheduled.ics'] = { :mime_type => 'text/calendar',
                              :content => cal.to_ical }

        mail(to: @manager.try(:email),
             subject: "Conversation is scheduled with #{@participant.full_name}",
             template_name: 'scheduled_manager')
      elsif opts[:send_to] == 'participant'
        cal = calender_event(@conversation, @manager, "Conversation is scheduled with #{@manager.full_name}", "A conversation is scheduled with Mr/Mrs #{@manager.full_name} on #{@conversation.starting_time}")  
        attachments['conversation_sheduled.ics'] = { :mime_type => 'text/calendar',
                              :content => cal.to_ical }

        mail(to: @participant.try(:email),
             subject: "Conversation is scheduled with #{@manager.full_name}",
             template_name: 'scheduled_participant')
      end
    end
private 

def calender_event(conversation, manager, summary, description)
      cal = Icalendar::Calendar.new
      cal.event do |e|
        e.dtstart     = Icalendar::Values::Date.new(conversation.startime.to_date.strftime("%Y%m%dT%H%M%S%Z"))
        e.dtend       = Icalendar::Values::Date.new(conversation.end_time.strftime("%Y%m%dT%H%M%S%Z"))
        e.summary     = summary
        e.description = description
        e.ip_class    = "PRIVATE"
        e.organizer = Icalendar::Values::CalAddress.new("mailto:#{manager.try(:email)}", cn: manager.try(:full_name))
      end
      cal
    end

All we need to do is send an attachment to the email setting the proper mime type to ‘text/calendar’ and the content by calling the ‘to_ical’ method on the event and it returns the calender object.

With proper email templates I do receive the emails with Calendar events and I can add this event to my google calendar. I can update the event details etc.

Advertisements