← Back to Upcase

Sending an email with a paperclip attachment


(Grant Spilsbury) #1

Hi,
I want my user to select a file to be attached to an email. Am I on the right track? I’m not sure how to attach the file to send.

Model

class Newsletter < ActiveRecord::Base
has_attached_file :letter
  attr_accessible :letter
end

Controller

class NewslettersController < ApplicationController
    def new
        @newsletter = Newsletter.new
    end

    def create
        @newsletter  = Newsletter.create( params[:newsletter] )
        NewsletterMailer.send_newsletter(@newsletter).deliver
    end
end

View

<%= form_for  @newsletter do |form| %>
  <%= form.file_field :letter %>
  <%= form.submit 'Send' %>
<% end %>

Mailer

class NewsletterMailer < ActionMailer::Base
  def send_newsletter(letter)
    # Not sure how to attach / read the file
    attachments = @letter
    mail(:to => 'name@spam.com', :subject => "Newsletter")
  end
end

(Chad Pytel) #2

Hi Grant,

You’re on the right track. In order to add the attachment to the email, you want to add it to the attachments hash in the mailer.

You can read more about this here: http://guides.rubyonrails.org/action_mailer_basics.html#sending-emails-with-attachments

Please let me know if you have any more questions on this.

thanks,
-Chad