How to Preview All ActionMailer Mails in the Browser

Notice: this needs to be admin/development only, since it can be really dangerous in the wrong hands… (uses eval or param…)

  • Developers see what they are dooing (just hit Refresh)
  • Livesaver for HTML Emails
  • Non-developers can check alignment/spelling/… sooo easy
  • Generated mails can be shared through url so no need for forwarding/screenshots

View
Just make a form that submits:

  • the method you want to call
  • list of arguments to use
  <%form_tag({:action=>'make_mail'}, :method=>:get) do%>
    <%=select_tag :method_name, options_for_select(UserMailer.public_instance_methods(false).sort)%>
    Models: Product.find(12322) / String: "abc" / Numbers: 123 / Array: [1,2,3]
    <table>
      <%5.times do |i|%>
        <tr>
          <td><%=i%></td>
          <td><%=text_field_tag "args[]", '', :style=>'width:300px'%></td>
        </tr>
      <%end%>
    </table>
    <%=submit_tag 'Preview'%>
    <%=submit_tag 'Send'%>
  <%end%>
<%end%>

Controller
Evals the ‘args’ and send or previews the mail.

def make_mail
  args = params[:args].map{|arg| eval arg}.compact

  if params[:commit]=='Preview' #preview button
    @text = UserMailer.send("create_#{params[:method_name]}", *args).body
    if @text =~ /<body>/
      render :text=>@text
    else
      render :text=>"<pre>#{@text}</pre>"
    end
  else #Send button
    UserMailer.send("deliver_#{params[:method_name]}", *args)
    flash[:notice] = 'Mail sent!'
    redirect_to params.merge(:action=>:index)
  end
end

Happy mail preview too you 😀

Advertisements

2 thoughts on “How to Preview All ActionMailer Mails in the Browser

  1. While the idea is nice, “eval”ing arguments submitted by a user is an incredibly large security thread.

    You cannot be serious to post this code on a website. Someone might actually use it!

  2. Its only meant to be used by programmers/admins that know what they do, no real user should ever use it of course, this would be madness 😉
    e.g. I have it disabled when not in development mode.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s