如何在rails中创建ICS并将其作为附件发送到邮件中?
答案 0 :(得分:14)
这可以使用ri_cal gem完成: 要创建要创建事件的事件ics文件:
event = RiCal.Event do
description "MA-6 First US Manned Spaceflight"
dtstart DateTime.parse("2/20/1962 14:47:39")
dtend DateTime.parse("2/20/1962 19:43:02")
location "Cape Canaveral"
add_attendee "john.glenn@nasa.gov"
alarm do
description "Segment 51"
end
end
然后在事件上使用.export(stream)
(这会将事件插入到仅包含此事件的包装器日历中,因此您不必自己包装它)。
可以将流设置为可以按照Andy建议的方式附加的文件,也可以在没有stream参数的情况下调用此方法,该参数将返回可以按原样放入附件的字符串。这看起来像这样:
class UserMailer < ActionMailer::Base
def send_event_email(user, event)
attachments['event.ics'] = event.export()
mail(:to => user.email, :subject => "Calendar event!")
end
end
答案 1 :(得分:1)
使用ActionMailer
(API documentation),只需生成文件并将其添加到attachments
:
class ApplicationMailer < ActionMailer::Base
def send_ics(recipient)
attachments['event.ics'] = File.read('path/to/event.ics')
mail(:to => recipient, :subject => "Calendar event!")
end
end
您可以在不将文件实际保存到文件系统的情况下执行此操作,但我会将此练习留给您。
答案 2 :(得分:1)
将此gem添加到您的Gemfile
gem 'mail'
gem 'icalendar'
您必须在config/enviroment.rb
内配置邮件gem,例如RoR 4.2
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
# Initialize sendgrid
ActionMailer::Base.smtp_settings = {
:user_name => 'username',
:password => 'password',
:domain => 'something.com',
:address => 'smtp.something.com',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
用户模型
has_may :calendar_events
字段
CalendarEvent模型
belongs_to :user
字段
应用/邮寄者/ mail_notifier.rb 强>
class MailNotifier < ActionMailer::Base
default from: 'test@something.com'
def send_calendar_event(calendar_event, organizer)
@cal = Icalendar::Calendar.new
@cal.event do |e|
e.dtstart = calendar_event.start_time
e.dtend = calendar_event.end_time
e.summary = calendar_event.title
e.organizer = "mailto:#{organizer.mail}"
e.organizer = Icalendar::Values::CalAddress.new("mailto:#{organizer.mail}", cn: organizer.fullname)
e.description = calendar_event.description
end
mail.attachments['calendar_event.ics'] = { mime_type: 'text/calendar', content: @cal.to_ical }
mail(to: calendar_event.user.mail,
subject: "[SUB] #{calendar_event.description} from #{l(calendar_event.start_time, format: :default)}")
end
end
现在,您可以使用以下代码从控制器调用MailNotifier
MailNotifier.send_calendar_event(@calendar_event, organizer_user).deliver