Sending attachment with Actionmailer in RubyonRails on-the-fly

Normally Models upload files.

The actual file is accessible via the tempfile accessor, though some of its interface is available directly for convenience.

Uploaded files are temporary files whose lifespan is one request. When the object is finalized Ruby unlinks the file, so there is no need to clean them with a separate maintenance task.

The magic is within rails application with ActionDispatch Module.And you can achieve it in just 2 steps.

Here i am using Rails 3.2.13 and Ruby 1.9.3

Here is the form where i am embedding the attachment(my form is in haml format),


= form_for(sendmail,:url=>"/send_email", :html=>{:class => "form",:method=>"post",:id=>"send-mail-popup",:multipart => true}) do |f|
...
...
= file_field_tag :attachment,:class=>"form-control btn-metis-7 btn-file"
...

In Controller,


    def send_email
        if !params[:attachment].nil? && !params[:attachment].blank?
              file = params[:attachment].tempfile.path
              file_name = params[:attachment].original_filename
        else
              file = ""
              file_name = ""
        end              
        Notification.send_email(params[:to],params[:cc],params[:bcc],params[:subject],
params[:message],file_name,file).deliver
        render :text => "success"
    end

In Action Mailer, add these below lines,


    class Notification < ActionMailer::Base
      default from: "no-reply@example.com"

def send_email(to,cc,bcc,subject,msg,file_name,file) @message = msg if file != "" attachments[file_name] = File.read(file) end mail(to: to, cc: cc,bcc: bcc, subject: subject) end end

Hope it will help you.Thanks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s