rubyemailpony

How to use body erb template in Mail gem?


I would like to use as body in Mail erb template. It works when I set up it on Pony gem.

post 'test_mailer' do
  Mail.deliver do
    to ['test1@me.com', 'test2@me.com']
    from 'you@you.com'
    subject 'testing'
    body erb(:test_mailer) # this isn't working
  end
end

private

fields = [1, 2] # some array

ERB file

<% fields.each do |f| %>
  <%= f %>
<% end %>

Solution

  • Assuming your original Sinatra route using Pony looked something like this:

    post 'test_mailer' do
      Pony.mail :to => ['test1@me.com', 'test2@me.com'],
                :from => 'you@you.com',
                :subject => 'testing',
                :body => erb(:test_mailer)
    end
    

    You can see that the email attributes here are specified by a Hash. When switching to using the Mail gem, it's attributes are defined by a block which gets called in a specific context so that these special methods are available.

    I think the problem may have something to do with calling erb inside the block. Here's a few things you can try:

    Try generating the ERB in a way that can be passed into the block:

    post 'test_mailer' do
      email_body = erb :test_mailer, locals: {fields: fields}
      Mail.deliver do
        to ['test1@me.com', 'test2@me.com']
        from 'you@you.com'
        subject 'testing'
        body email_body
      end
    end
    

    Or calling ERB globally instead of using the sinatra helper:

    post 'test_mailer' do
      context = binding
      Mail.deliver do
        to ['test1@me.com', 'test2@me.com']
        from 'you@you.com'
        subject 'testing'
        body ERB.new(File.read('views/test_mailer.erb')).result(context)
      end
    end