Archive | Mailer RSS for this section

Rails 4 Simple Form and Mail Form To Make Contact Form

In this tutorial I will be using the following gems:

  • Rails 4
  • mail_form 1.5
  • simple_form 3
  • Twitter Bootstrap

This tutorial will assume that you already have twitter bootstrap installed have your mailer configured. If your mailer is not configured you can look at this post to set it up using local environment variables: Setting Up Mailer Using Devise For Forgot Password

I will show you how to set up a simple contact form which will not save anything into the database, use a hidden field to check against computers sending spam, and configure flash messages to make the form look even better!

Installing Gems

First you will need to add mail_form and simple_form into your “Gemfile”.

gem 'mail_form'
gem 'simple_form'

Then you can run bundle install to install the gems.

Creating the Contact Form

First we will create the route: “config/routes.rb” Your route should look like this:

match '/contacts',     to: 'contacts#new',             via: 'get'
resources "contacts", only: [:new, :create]

Next you will need to make a controller: “app/controllers/contacts_controller.rb” Within the contacts controller it should look like this:

class ContactsController < ApplicationController
  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    @contact.request = request
    if @contact.deliver
      flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
    else
      flash.now[:error] = 'Cannot send message.'
      render :new
    end
  end
end

Next we will need a model: “app/models/contact.rb” Inside the model it should look something like this:

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha  => true

  # Declare the e-mail headers. It accepts anything the mail method
  # in ActionMailer accepts.
  def headers
    {
      :subject => "My Contact Form",
      :to => "your_email@example.org",
      :from => %("#{name}" <#{email}>)
    }
  end
end

Make sure to enter the what you want the subject of the message to be when it is sent to you. You also need to tell the mailer where you would like to send the messages to. Then we will need to create the views for the form. In “app/views/contacts/new.html.erb” you should put something like this:

<div align="center">
  <h3>Send A message to Us</h3>

  <%= simple_form_for @contact, :html => {:class => 'form-horizontal' } do |f| %>
    <%= f.input :name, :required => true %>
    <%= f.input :email, :required => true %>
    <%= f.input :message, :as => :text, :required => true %>
    <div class= "hidden">
      <%= f.input :nickname, :hint => 'Leave this field blank!' %>
    </div>
    <div>
      </br>
      <%= f.button :submit, 'Send message', :class=> "btn btn-primary" %>
    </div>
  <% end %>
</div>


The send message button will be from twitter bootstrap. The nickname attribute will be hidden so that no one can fill it out but computers will fill it out. This will determine whether the message is coming from a computer or not.

Next we can add styling for the alert messages. In the file “app/views/contacts/create.html.erb” you should add this to put the alerts into flash messages.

<div>
  <% flash.each do |key, value| %>
    <div>
      <a href="#" data-dismiss="alert">×</a>
        <%= value %>
    </div>
  <% end %>
</div>

You will also need to add some styling in the style sheets. In “app/assets/stylesheets/custom.css.scss” you can add this to hide the nickname field we create earlier.

.hidden { display: none; }

In the same file you should add some styling for the flash notifications. I have set alert-error and alert-alert to be red to be used when things fail. I also have set alert-success and alert-notice to be green when things are successful.

/*flash*/

.alert-error {
background-color: #f2dede;
border-color: #eed3d7;
color: #b94a48;
text-align: left;
}

.alert-alert {
background-color: #f2dede;
border-color: #eed3d7;
color: #b94a48;
text-align: left;
}

.alert-success {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #468847;
text-align: left;
}

.alert-notice {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #468847;
text-align: left;
}

Now you have a working contact form. You can go to localhost:3000/contacts to see the form in action!

This tutorial was made using the following resources:

Setting Up Mailer Using Devise For Forgot Password

In this tutorial I will show you how to set up the mailer for the forgot password feature in Devise. In the tutorial I will be setting up a Gmail account and I will show you how its done using local environment variables. I will also be using Heroku and Foreman to set up environment variables.

I am using Rails 4 and Devise 3 for this tutorial.

Seting Up Development Environment

First we will set up the development mailer for use on your local machine. In “config/environments/development.rb” you should already have included

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

when you installed devise.

Next you should turn on the option to raise an exception if there is an error when sending an email. You can do this by including

config.action_mailer.raise_delivery_errors = true

in the same file. Next we will add the email delivery method. You should leave the values as they are because I will show you how to set your email information later using local environment variables. Using local environment variables will allow you to hide your email information on open source software sites like Github. In the same file add

config.action_mailer.delivery_method = :smtp

config.action_mailer.smtp_settings = {
address: “smtp.gmail.com”,
port: 587,
domain: ENV[“GMAIL_DOMAIN”],
authentication: “plain”,
enable_starttls_auto: true,
user_name: ENV[“GMAIL_USERNAME”],
password: ENV[“GMAIL_PASSWORD”]
}

Make sure that you leave the values as they are in order to allow you to set the local variables later on.

Setting Up Production Environment

Now you will need to edit the file “config/environments/production.rb”. We will be adding very similar things to this file. First you can add:

config.action_mailer.default_url_options = { :host => 'yoursite.herokuapp.com' }

NOTE: You may also need to add this line. When I was setting up the mailer, I did not find this line in any other tutorials. I had the development mailer working, however I could not get heroku to work. I received this error in the heroku logs:

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

I found the answer here: ActionView::Template::Error: Missing host to link to on stackoverflow. If you come across this, then add:

Rails.application.routes.default_url_options[:host] = 'yoursite.herokuapp.com'

to your production.rb file.

Next you will have to add in these lines. Once again make sure that you leave the variables as they are.

config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"

config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: ENV["GMAIL_DOMAIN"],
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}

Devise includes its own emails for the mailer. These can be found at “app/views/devise/mailer/”

Adding Local Environment Variables

In this section you will set local variables to your local host and your production site (Heroku).

First create a file in the root directory called “.env”. This is the file we will use to hold our environment variables so that the whole world does not have access to them. Within “.env” you should type:

GMAIL_DOMAIN=yoururl.com
GMAIL_USERNAME=support@yoururl.com
GMAIL_PASSWORD=password12345

this time filling in your information for your gmail. The GMAIL_DOMAIN is gmail.com and you will use your own information for the rest of it. In this case we set the variables inside the file and within the development and production files, it will look for these variables.

Heroku recommends using a gem called Foreman. This will allow us to use our .env file by accessing the local variables before starting the application. We are already using Heroku for production so we should only install Foreman for testing and development. Open the Gemfile and add:

group :development, :test do
gem 'foreman'
end

Then run bundle install and you will have added the file. Next we will create a file in the root directory called “Procfile”. This file will tell the application which files should be run. Inside the Procfile you should add:

web: bundle exec rails s

Next it is very IMPORTANT that you update your .gitignore file. Failure to update your .gitignore may result in your information becoming public to the world. It is a good idea to add in the Procfile to ensure that Heroku does not receive a R11 – Bad Bind Error.

.env
Procfile

Now you will need to add the local environment variables to Heroku. This link to Heroku can give you a better idea of how it works. To add the variables to Heroku, make sure you are in the root directory and type:

heroku config:add GMAIL_PASSWORD=password12345 GMAIL_USERNAME=support@yoururl.com GMAIL_DOMAIN=yoururl.com

replacing the values with your real information. With Foreman installed, you can now start your application and test out the mailer for the local machine. You can use

foreman start

to start your web application.

This tutorial was made using the following resources: