Site icon Mailtrap

Ruby on Rails Contact Form

Creating a contact form in a Ruby on Rails application is a common task for developers. Having a contact form is a simple way for a website or an app user to send messages to the administrator.

In this article, using real code examples, we’ll cover how to: create a Ruby on Rails contact form, ensure it sends the information once submitted, and finally test it. 

How to create a Ruby on Rails contact form?

Building a contact form can seem confusing, but with a few simple steps, you’ll have a functional contact form up and running in no time. 

If you still need to do it, the first and obvious step is to create a new Rails application by running this command in your terminal or command prompt: 

rails new myapp -c bootstrap

Now you’ll need to generate a new controller that will handle requests from the user and interact with a model that manages the flow of the application’s data. Create it by running this command:

rails generate controller contact_form

Once you’ve created the contact_form_controller.rb file, in the view folder of your controller, create a new file named new.html.erb and add the relevant code to create a form. Here is an example:

<%= form_with scope: :contact_form, url: contact_form_index_path, method: :post, local: true, class: "container" do |form| %>
  <div class="form-group">
    <%= form.label :name %>
    <%= form.text_field :name, class: "form-control" %>
  </div>
  <div class="form-group">
    <%= form.label :last_name %>
    <%= form.text_field :last_name, class: "form-control" %>
  </div>
  <div class="form-group">
    <%= form.label :email %>
    <%= form.email_field :email, class: "form-control" %>
  </div>
  <div class="form-group">
    <%= form.label :message %>
    <%= form.text_area :message, class: "form-control" %>
  </div>
  <%= form.submit "Submit", class: "btn btn-primary" %>
<% end %>

*** Note: The above example shows a standard Contact Us form with the basic text fields and a submit button. However, the same would apply to a more advanced form with multiple text fields, select boxes, and checkboxes.

Next, in the controller, make a new create method to handle the form submission. This method lets you access the form data using the params hash and perform necessary actions, such as saving the data to a database.

You want the user to see a success message displayed after the form is submitted, so make sure to add the flash hash in the controller action. 
Here is how the full code would look like:

def create
    @name = params[:contact_form][:name]
    @last_name = params[:contact_form][:last_name]
    @email = params[:contact_form][:email]
    @message = params[:contact_form][:message]

    # Perform any necessary actions with the form data
    flash[:success] = "Your message has been sent successfully."
    redirect_to :root
end

For the flash message to be displayed, in your layout file, add the below code that will check for any messages in the flash hash and display them as a regular Bootstrap alert based on the indicated key (success, error, etc.).

<% flash.each do |key, value| %>
  <div class="alert alert-<%= key %>">
    <%= value %>
  </div>
<% end %>

Alternatively, you can use the flash.now hash without redirect_to, so the message is available only in the current request, meaning the message will be displayed immediately, and the user will stay on the same page after submitting the form.

Add this to your config/routes.rb file:

root "contact_form#new"
resources :contact_form, only: %i[new create]

With these few straightforward steps, you can create the foundation for a simple contact form. The next part is to add the relevant code to make the contact form send emails with the submitted information.

How to send emails with a Ruby on Rails contact form?

Available methods overview

There are several ways for a submitted form to send an email in Ruby on Rails. Each method has advantages and disadvantages, so you should choose one that best suits your needs. It is important to note that the one that is most convenient and commonly used is ActionMailer. Nevertheless, let’s quickly review all of them.

Let’s review all the methods and see how to apply those most favorable.

  1. Using the mail library: a built-in library in Ruby. 
  1. Using ActionMailer: a built-in Rails module. 
  1. Using a gem: custom packaged Ruby code that gives access to methods. 
  1. Using an external service
  1. Using JavaScript

Sending Code Example 

In our example, we’ll demonstrate how to have the contact form send the email using ActionMailer with credentials from Mailtrap Email Delivery Platform which is comprised of Email Sending and Email Testing.

Using the platform, businesses and individuals can cover all their email-related needs in one place: testing, sending, and in-depth tracking to control how email infrastructure works and performs.


First, let’s review the ActionMailer method with Email Sending SMTP credentials.

After signing up to Mailtrap and creating a new inbox, in your Rails application, from config/environments/development.rb file, configure ActionMailer to SMTP and set your unique credentials:  

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :user_name => 'username example',
  :password => 'password example',
  :address => 'live.smtp.mailtrap.io',
  :domain => 'live.smtp.mailtrap.io',
  :port => '587',
  :authentication => :plain,
  :enable_starttls_auto => true
}

Now we need a mailer model to send our email. Since, in this example, we’re using ActionMailer, we can generate one:

rails generate mailer Notifier

And add a simple method to forward the message that the user entered in our form to our mailbox.

class NotifierMailer < ApplicationMailer
  default to: "your@email-address",
    from: "contact@your-domain"

  def simple_message(first_name, last_name, email, message)
    mail(
      "reply-to": email_address_with_name(email, "#{first_name} #{last_name}"),
      subject: "New contact form message",
      body: message
    )
  end
end

Add a line to use this mailer in contact_form_controller.rb create method:

NotifierMailer.simple_message(@name, @last_name, @email, @message).deliver_now

Here’s how the full create method should look:

def create
    @name = params[:contact_form][:name]
    @last_name = params[:contact_form][:last_name]
    @email = params[:contact_form][:email]
    @message = params[:contact_form][:message]

    NotifierMailer.simple_message(@name, @last_name, @email, @message).deliver_now
    flash[:success] = "Your message has been sent successfully."
    redirect_to :root
end

Now when we fill the contact form on our local webpage, we should receive an email from it right away.

Alternatively, the data from the submitted form can be sent via Email Sending API rather than SMTP. For detailed gem documentation, check out the Official Mailtrap Ruby client GitHub page.

In your Rails application, add the mailtrap gem to your Gemfile, and run bundle install to install it: 

gem 'mailtrap'

After that, we need to update our Action Mailer settings in the config/environments/development.rb file, so that it uses the Mailtrap API instead of specifying the SMTP details:

config.action_mailer.delivery_method = :mailtrap
config.action_mailer.mailtrap_settings = {
  api_key: ENV.fetch('MAILTRAP_API_KEY')
}

This allows us to keep our NotifierMailer in the controller code for the create method, and it will be automatically using the Mailtrap API to send the contact form emails.

Testing your contact form with Mailtrap Email Testing

Testing any type of form before deploying is always a good idea to ensure its functionality. By testing the form, developers can identify and fix any errors that may occur, such as incorrect data validation or missing fields. This prevents users from encountering such issues when the form is live. Moreover, testing the form allows checking that the email is delivered to the correct recipient and that it contains the correct information.

By intercepting and capturing all sent emails, Mailtrap Email Testing allows you to test email sending in a development environment without the risk of spamming users. After that, you can evaluate the compatibility of your email’s HTML/CSS with top email clients, see how emails will appear in various email clients and on different devices, get a detailed spam analysis, review raw email data, and so much more.

To test the emails that are sent through your form, configure the below SMTP credentials for your staging or development environment and list your username and password. 

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :user_name => 'username example',
  :password => 'password example',
  :address => 'sandbox.smtp.mailtrap.io',
  :domain => 'sandbox.smtp.mailtrap.io',
  :port => '2525',
  :authentication => :cram_md5
}

With these settings, any email sent from the application will be intercepted by Mailtrap Email Testing and can be viewed in the dashboard.

Read one of our relevant articles for more tips on performing email validation in a Ruby on Rails app.

Conclusion

By following the steps outlined in this article, you can create a simple and easy-to-use contact form that can be quickly set up and tested. However, it’s important to prevent spam and ensure that only legitimate messages are sent through the form. One effective way to do this is by implementing a CAPTCHA test (Completely Automated Public Turing).

It’s also worth mentioning that there are many Ruby gems available that can assist with building your application and provide additional functionality. We hope you found this tutorial useful and if you’re interested in learning about other ways of sending email in Ruby in general, check this article out.

Exit mobile version