Posts Tagged with "email attachment"
Adding multiple email attachments with Ruby on Rails
JUN
20
2007
I was building some forms for a client that required the user be able to upload supporting documents along with the application. I had implemented emailable forms before with single attachments, but never multiple. Turns out, it was just as simple to do, I just needed to call the attach function for each file I wanted to attach.
Here is the method in my controller that calls the ActionMailer class to send the email, where params[:file1], params[:file2], and params[:file3] are the file_field_tag's from the form:
UPDATE: I've re-factored this after Shawn suggested that it could be simplified into an array and iterated over.
def submit_application @uploaded_files = [] @uploaded_files << params[:file1] @uploaded_files << params[:file2] @uploaded_files << params[:file3] ContactMailer.deliver_email_with_attachments(params[:application], @uploaded_files) flash[:notice] = 'Your application has been submitted. Thank you!' redirect_to application_home_url rescue Exception => ex logger.warn(ex.message) flash[:notice] = 'Uh oh! There was an error sending your application.' redirect_to :back end
And here is the ActionMailer method that attaches the files. I just need to iterate over the files, calling attach for each one.
def email_with_attachments(application_fields={},files=[])
@headers = {}
@sent_on = Time.now
@recipients = 'client@domain.com'
@from = 'info@domain.com'
@subject = 'Here are some file attachments'
application_fields.keys.each {|k| @body[k] = application_fields[k]}
# attach files
files.each do |file|
attachment "application/octet-stream" do |a|
a.body = file.read
a.filename = file.original_filename
end unless file.blank?
end
end
The "application/octet-stream" is the generic MIME type for attaching unknown file types.
Pretty simple!
Tagged: tutorial, rails, email attachment, actionmailer
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.