Sending email from Rails application

 Date: July 15, 2013

It took me a while to configure sending email from Rails application. I went through many different tutorials, blogs, StackOverflow posts etc. Step, by step I found working configuration.

To send emails I use ActionMailer. First you need to generate mailer:

rails generate mailer UserMailer

It will create UserMailer class in app/mailers directory. In this class we need to define our method for sending emails:

class UserMailer < ActionMailer::Base
  default from: "from@example.com"
  def send_email(user_email, content)
  	@user_email = user_email
  	@content = content
  	mail(to: "your@mail.com", subject: "Email from mysite.com")
  end
end

Then in the directory app/views/user_mailer we need to create template for our email: send_email.html.erb (this name must match the name of action created in UserMailer class):

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>
      From: <%= @user_email %>
    </p>
    <p>
      <%= @content %>
    </p>
  </body>
</html>

(*) If you do not want to send html you can create plain text and name file send_email.text.erb.

Now, the hardest part. Configuration of smtp. You need to add it to config/environments/development.rb (or test.rb or production.rb). I found this configuration working for gmail:

# set delivery method to :smtp, :sendmail or :test
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  # these options are only needed if you choose smtp delivery
  config.action_mailer.smtp_settings = {
    :address        => 'smtp.gmail.com',
    :port           => 587,
    :domain         => 'gmail.com',
    :authentication => :login,
    :user_name      => 'your_gmail@gmail.com',
    :password       => 'your_password',
    :enable_starttls_auto => true
  }

The last thing is call ActionMailer from our app:

UserMailer.send_email(params[:from], params[:content]).deliver

Form for sending email can looks like that:

<%= form_tag '/send_email', method: 'post' do %>
	<div class="field">
		Email
    <%= email_field_tag :from %>
  </div></p>
<p>	<div class="field">
		Content
    <%= text_area_tag :content, nil, rows: 10, cols: 25 %>
  </div></p>
<p>  <div class="actions">
    <%= submit_tag "Send", class: "btn btn-large btn-primary" %>
  </div>
<% end %>

For that you need to configure action in controller and match route e.g.:

match '/send_email', to: 'your_controller#your_action'

Method send_mail (from UserMailer class) can have as much parameters as you need. It can be also 0. In above example, the params are just rendered in the email template (send_email.html.erb file).

 Tags:  programming

Previous
⏪ Getting started with Ruby on Rails

Next
Sign in with facebook (OAuth): how to and threats ⏩