Creating a contact form mailer in merb using sendmail and merb-mailer

I posted all this in the wiki here, but in case it changes and simply as documentation for myself, I am reposting it here. Much of it is pieced together from various places.

===== Installation =====
The gem merb-mailer is already installed as part of the standard merb installation via sudo gem install merb. See http://github.com/wycats/merb/tree/master

But if you are missing it, do:

sudo gem install merb-mailer

It will install “mailfactory”:http://mailfactory.rubyforge.org/ gem and “mime-types”:http://mime-types.rubyforge.org/ that mailfactory depends on.

===== Configuration =====
Assuming you created an app using ‘merb-gen app’, merb-mailer will already be listed in config/dependencies.rb. If you started your app using ‘merb-gen core’ then you will need to include merb-mailer as a dependency like the following:

In init.rb, put this at the top

1
require 'config/dependencies.rb'

In config/dependencies.rb

1
2
3
4
5
6
# dependencies are generated using a strict version, don't forget to edit the dependency versions when upgrading.
merb_gems_version = "1.0"
dm_gems_version   = "0.9.6"
 
# For more information about each component, please read http://wiki.merbivore.com/faqs/merb_components
dependency "merb-mailer", merb_gems_version

In init.rb configure for sendmail (see below for other config options like smtp). Alternatively, you can put this in development.rb if your production.rb email setup might use smtp instead or vice versa. Development.rb and production.rb will override the init.rb file.

1
2
3
4
5
Merb::BootLoader.after_app_loads do
  # This will get executed after your app's classes have been loaded.
  Merb::Mailer.config = {:sendmail_path => '/usr/sbin/sendmail'}
  Merb::Mailer.delivery_method = :sendmail
end

(Type “which sendmail” to verify where sendmail is located on your machine.)

See http://merbivore.com/documentation/current/doc/rdoc/merb-mailer-1.0/index.html for documented config options.

===== Using Merb mailers =====
Merb separates out its mailers into its only little MVC so things work a little differently than you might be used to with Rails. But it’s for the better.

==== First, setup the mailer. ====

merb-gen mailer contact

This will generate a mailer controller and a mailer view under app/mailers

Open up app/mailers/contact_mailer.rb and make it look like the following:

1
2
3
4
5
6
7
8
class ContactMailer < Merb::MailController
 
  def notify
    @user = params[:user]
    render_mail
  end
 
end

Edit app/mailers/views/contact_mailer/notify.text.erb

1
Tall tube socks with red stripes. The right sock has a large whole near the big toe.

==== Now put the mailer to use inside a controller ====
**Generate a static controller**

merb-gen controller static

**Create an index action and contact action for the static controller**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Static < Application
 
  # ...and remember, everything returned from an action
  # goes to the client...
  def index
    render
  end
 
  def contact
    send_mail(ContactMailer, :notify, {
      :from => 'yourself@email.com',
      :to => "someoneelse@gmail.com",
      :subject => "Free gym socks. Used!"
    })
 
    render
  end
end

**Make sure your routes are setup properly in router.rb**

1
2
3
4
5
Merb::Router.prepare do
  match('/index').to(:controller => "static", :action => "index").name(:index)
  match('/contact').to(:controller => 'static', :action =>'contact').name(:contact)
  match('/').to(:controller => 'static', :action =>'index')
end

**Make sure your views (static/index.html.erb and static/contact.html.erb) are setup to some degree**

1
2
3
4
5
# index.html
<h2>Home page</h2>
 
# contact.html
<h2>Contacto!</h2>

**Navigate to http://localhost:4000/contact and it should work!**

See http://github.com/wycats/merb/tree/master/merb-mailer for additional details.

It you have problems make sure postfix is running with sudo postfix stop and then sudo postfix start). You should also see the email get sent in your merb development server output. It should look something like the following:

merb : worker (port 4000) ~ notify sent to someoneelse@gmail.com about =?utf-8?Q?Free_gym_socks._Used!?=

===== Creating a contact form =====
This assumes you’ve followed the above instructions so far. This also assumes usage with datamapper.

Create a contact model

merb-gen model contact

Edit models/contact.rb to look like the following:

1
2
3
4
5
6
7
8
9
10
11
class Contact
  include DataMapper::Resource
 
  property :id, Serial
  property :name, String, :nullable => false
  property :email, String, :nullable => false
  property :message, String, :nullable => false
 
  validates_format :email, :as => :email_address
 
end

Edit the static controller’s contact action. This renders the contact page unless the form is submitted using request.post? Then the contact information is saved with datamapper (but not to the database) and our ContactMailer notify action is used to send the mailer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# static.rb controller
  def contact
    if request.post?
      @contact = Contact.new(params[:contact])
      if @contact.valid?
        send_mail(ContactMailer, :notify, {
          :from => @contact.email,
          :to => 'scott@scottmotte.com',
          :subject => "New message from contact form"
        }, { :contact => @contact})
        render "Thank you. Your message has been sent."
      else
        render :contact
      end
    else
      @contact = Contact.new
      render
    end
  end

Edit the contact action’s view at views/static/contact.html.erb

1
2
3
4
5
6
7
8
<h2>Contact</h2>
<%= error_messages_for @contact %>
<%= form_for @contact, :action => url('contact') do %>
     <p><%= text_field :name, :label => 'Name' %></p>
     <p><%= text_field :email,  :label => 'Email' %></p>
     <p><%= text_area :message, :label => 'Message' %></p>
     <%= submit 'Send' %>
<% end =%>

Your contact form should now send emails and do validations if items aren’t filled in. We still have to pass the values to the emailed message though so let’s take a look at our mailers/contact_mailer.rb and its prospective view to do this.

Edit contact_mailer.rb

1
2
3
4
5
6
7
8
9
class ContactMailer < Merb::MailController
 
  def notify
    # use params[] passed to this controller to get data
    @contact = params[:contact]
    render_mail
  end
 
end

Edit notify.text.erb

1
2
3
4
5
6
7
Name: <%= @contact.name %>
 
Email: <%= @contact.email %>
 
Message:
 
<%= @contact.message %>

**That’s it. You’re done.** You could also customize things a bit here, by creating a global from email in devlopment.rb and production.rb by putting something like ‘SITE_EMAIL = “you@domain.com”‘ at the end of those files.

Comments

  1. Matt Aimonetti | November 19, 2008

    thanks for sharing, that’s really appreciated. (and thanks for posting your tutorial in the wiki)

    -Matt