Last week I covered two topics, Emailing in Ruby on Rails and also Uploading Documents in Ruby on Rails using the attachment_fu plugin. This post will join them both together to teach you how to add attachments to emails. It is important that you read the first to posts before continuing.
Adding attachments to emails is a relatively easy task. The first step is to modify the way the email gets the body to be a “part”. It is just a way of splitting up the content to allow multiple content types (eg attachments). Then we modify the action mailer method to accept an array of files or an object that has many documents as a reference. In the below scenario, the documents are part of the loan object. After that, you need to add a loop to go through each file and attach them.
part :content_type => "text/plain" do |p|
p.body = render_message("loan_notification", :loan=> loan)
end
loan.documents.each do |appFile|
attachment :content_type => "application/octet-stream", :body => File.read(RAILS_ROOT + "/public" + appFile.public_filename), :filename => appFile.filename
end
It really is that simple. We loop through the files, set the content type to be “application/octet-stream” so that it can handle multiple file types. Then set the body to be the location of the file (as we used file storage in the previous post) and set the filename. I hope you enjoyed the post!
Cameron
|
Pingback: Tweets that mention http://blog.castitt.com/?p=23utm_sourcepingback -- Topsy.com