Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send a rendered view as an email rails

I would like to send what is normally a view as the body of an email.

Whats the simplest way to do this?

eg: I have pages/reports.html.erb and I want to send the page that you'd see if you visited that path as the body of an email.

Is there some way to take the html that is rendered and assign it to the body variable of an email?

Additionally, I'd like to include the PDF version as an attachment. (I'm using wicked_pdf)

def reports
  @email = params[:email]
  #something here?
  respond_to do |format|
    format.html
    format.pdf do
      render :pdf => "usage_report"
    end
  end
end

note: I'm using rails 3.1 with mongoid 2 for the DB and sendgrid on heroku if that helps

EDIT: What I ended up doing:

replace #something here? with:

email_obj = {}
email_obj.to = params[:email]
email_obj.from = '[email protected]'
email_obj.subject = 'Report'
email_obj.body = render_to_string(:template => "pages/reports", :layout => false)
ReportsMailer.deliver_report(email_obj).deliver

and in the mailer class mailers/reports_mailer.rb

class ReportsMailer < ActionMailer::Base
    default from: "[email protected]"
    def deliver_report(email)
        @email = email
        mail( :to => @email.to,
        :subject => @email.subject, 
        :from => @email.from)
    end
end

and in reports_mailer/deliver_report.html.erb

<%= render :inline => @email.body %>
like image 696
Hayk Saakian Avatar asked Dec 27 '12 04:12

Hayk Saakian


1 Answers

The rails mailer views are stored in a sub folder in views by the name of the mailer just like controller views. It is hard to say if this will work completely for you not knowing what the view/controller for that method looks like but what you could do is take the rendering for that page and turn it into a partial which you can then render in both the controller view and the mailer view as such:

given a partial: _my_partial.html.erb

within the views:

render "my_partial"

Using the partial you can even pass any variable that would be necessary for the view to be rendered to it with:

render "my_partial", :variable => variable

Update: This may be of interest as well: Rendering a Rails view to string for email

like image 95
Jay Truluck Avatar answered Oct 07 '22 20:10

Jay Truluck