Recipe 9.4. Attaching Files to Email Messages


Problem

Contributed by: Dae San Hwang

You want to attach files to your email messages. For example, you want to attach the welcome.jpg file in your application's root directory to a welcome email message being sent to new customers.

Solution

This solution uses the CustomerMailer class from Section 9.2."

To attach a file to an email message, you call the part method with a Hash object containing a MIME content type, a content disposition, and a transfer encoding method for the file you are attaching:

app/models/customer_mailer.rb:

class CustomerMailer < ActionMailer::Base   def welcome_message(cust_name, cust_email)     @subject    = "Welcome to Our Site"     @body       = {:name => cust_name, :email => cust_email}     @recipients = cust_email     @from       = "webmaster@yourwebsite.com"     @sent_on    = Time.now     part(:content_type => "image/jpeg", :disposition => "attachment; filename=welcome.jpg",          :transfer_encoding => "base64") do |attachment|       attachment.body = File.read("welcome.jpg")     end   end end

Note that there is a filename field for the content disposition. This is the filename the recipient will see; it is not necessarily the name of the file you have attached.

Discussion

You can attach as many files as you want by calling the part method repeatedly.

See Also

  • Section 9.2"

  • Section 9.5"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net