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 ."

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