0

Rails will helpfully send multipart email if there are multiple template types present (e.g. .txt and .html files for the same mailer action).

However, what if I want to do this without templates? Normally we specify body and content_type as arguments:

mail to: 'a@example.com', subject: 'Hello', body: 'Hi', content_type: 'text/html'

So how can this be achieved with multiple bodies having their own type?

mahemoff
  • 44,526
  • 36
  • 160
  • 222

1 Answers1

2
class TestMailer < ActionMailer::Base
  def welcome_email
    mail(to: 'example@example.com', subject: 'Welcome to My Awesome Site') do |format|
      format.html { render html: '<h1>Welcome XYZ!</h1>'.html_safe }
      format.text { render plain: 'Welcome XYZ' }
    end
  end
end

To use it call: TestMailer.welcome_email.deliver_now.

Documentation, section 2.4

MrShemek
  • 2,413
  • 1
  • 16
  • 20
  • 2
    This was working fine in Rails 4.2 and 5.0, but in 5.1 it fails with: `ActionView::MissingTemplate`. The documentation [section 2.11](https://guides.rubyonrails.org/action_mailer_basics.html#sending-emails-without-template-rendering) explains that to send without a template, use a body: parameter in the mail() call, but it doesn't explain how to deal with multipart emails. – Brent Nov 15 '18 at 18:19
  • @Brent I checked that with Rails 5.1.5 and no exception was raised – MrShemek Mar 08 '19 at 08:06