Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails mailer without view

Is it possible to have a Rails mailer without any view ?

When dealing with text-only mails, it would be cool to be able to put the body right in the mailer itself and not have to use a view for the action with just one line of text (or one I18n key).

In a way, I'm looking for something like ActionController's "render :text =>" but for ActionMailer.

like image 689
aurels Avatar asked Jan 26 '11 14:01

aurels


People also ask

How do I view Mailers in Rails?

Mailer views are located in the app/views/name_of_mailer_class directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the welcome_email method will be in app/views/user_mailer/welcome_email. html.

What is action_ mailer in Rails?

Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from ActionMailer::Base and live in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.

How does action mailer work?

Action Mailer allows emails to be sent now or later using . deliver_now or . deliver_later . The latter takes advantage of Active Job, which allows emails to be sent outside of the request response cycle, think asynchronously, which can make your application feel faster for the user.


2 Answers

Much simpler, just use the body option :

def welcome(user)
  mail to:       user.email,
       from:     "\"John\" <[email protected]>",
       subject: 'Welcome in my site',
       body:    'Welcome, ...'
end

And if you plan to use html, don't forget to specify that with the content_type option which is by default text/plain.

content_type: "text/html"


So with body option rails skips the template rendering step.

like image 104
Noémien Kocher Avatar answered Oct 17 '22 22:10

Noémien Kocher


I found the way by experimentation :

mail(:to => email, :subject => 'we found the answer') do |format|
  format.text do
    render :text => '42 owns the World'
  end
end

This is also said in the Rails Guide : http://guides.rubyonrails.org/action_mailer_basics.html at section 2.4

like image 20
aurels Avatar answered Oct 17 '22 21:10

aurels