Steps: 1. Install MailForm. Just edit your Gemfile adding the following:
gem 'mail_form'
2. Run bundle install to install MailForm.
3. If there is no already a controller created go ahead and create one. In my case I named it Contacts. This will be a base controller for my contact form. Run following to create one:
rails g controller Contacts index
4. Adjust contacts_controller.rb. Please note ContactForm is something we will need to add to our app/mailers folder. Don't forget to add strong parameters(contact_params).
class ContactsController < ApplicationController
before_action :contact_params, only: [:create]
def index
@contact = ContactForm.new
end
def create
@contact = ContactForm.new(params[:contact_form])
@contact.request = request
if @contact.deliver
flash.now[:notice] = 'Thank you for your message!'
render :index
else
flash.now[:error] = 'Cannot send message.'
render :index
end
end
private
def contact_params
params.require(:contact_form).permit(:name, :email, :message, :nickname, :captcha)
end
end
5. Create New Mailer class in app/mailers folder. FYI nickname here is just for Honeypot captcha implementation. You can read more about it here.
7. For the mail service I used Sendgrid. The easiest way to open a new account is through Heroku, go to addons page and just follow tutorial. Here is the LINK
8. Add SendGrid settings to config/environments/ and here to any ENV you want to use it. I added it to both dev and prod file. ENV['SENDGRID_USERNAME'] and ENV['SENDGRID_PASSWORD'] is easy to find in Heroku Config Vars. Also here is the SendGrid Dashboard link.