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: ""
  def send_email(user_email, content)
  	@user_email = user_email
  	@content = content
  	mail(to: "", subject: "Email from")

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>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
      From: <%= @user_email %>
      <%= @content %>

(*) 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        => '',
    :port           => 587,
    :domain         => '',
    :authentication => :login,
    :user_name      => '',
    :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_field_tag :from %>
<p>	<div class="field">
    <%= text_area_tag :content, nil, rows: 10, cols: 25 %>
<p>  <div class="actions">
    <%= submit_tag "Send", class: "btn btn-large btn-primary" %>
<% 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

⏪ Getting started with Ruby on Rails

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