The Sinatra Songbook Project

An Email Contact Form in Sinatra

In this ditty, I’m going to go through the steps needed to create a simple contact form page that sends you an email. This could easily be adapted for sending other types of emails through a web interface. In this tutorial I’m going to use my gmail account to send the email.

We are going to use Pony to send the emails, so first of all you’ll need to install the pony gem.

sudo gem install pony

To start with, we will put together the contact page form. This will be at the url /contact, the handler is easy:

get '/contact' do
erb :contact
end

The view code looks like this in erb (this should be saved in your views directory as contact.erb):

Basically all this does is fill in the fields required for Pony and sends the email using your own gmail account (make sure you put your own details in!). If this all works out you will get an email with the title ‘Daz has contacted you’.At the end of the code, the user is redirected to a success page, so that needs adding too:

get('/success'){"Thanks for your email. We'll be in touch soon."}

Obviously you will probably want to have a nicer page than that simple plaintext message, but you get the idea.

Heroku

Heroku allows you to use the Sendgrid addon to send emails. You can sign up for a free account (up to 200 emails a day) using the following code: