Sending emails is a crucial aspect of many web applications, and Ruby on Rails provides a powerful framework for handling email communication. In this article, we will explore how to configure and send SMTP (Simple Mail Transfer Protocol) emails from a Rails application. We’ll cover everything from setting up the SMTP configuration to creating and sending emails using Rails’ Action Mailer.

Setting up SMTP Configuration

Since we will be working in localhost - development environment, first we have to configure file: config/environments/development.rb and add following code (you can place it near the end-block):

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

    # SMTP settings
    config.action_mailer.smtp_settings = {
      :address              => ENV["HOST_SMTP"],
      :port                 => ENV["PORT_SMTP"],
      :user_name            => ENV["EMAIL"],
      :password             => ENV["EMAIL_PASSWORD"],
      :authentication       => "plain",
      :ssl                  => true,
    }

In this example we will also use environment variables (ENV[‘VARIABLE_NAME’]), insted of hardcoded values. With tiny bash script we can ask a user to fill in email credentials + SMTP configuration: project_root_folder/config_smtp.sh:

echo "SMTP Creation"
echo "-------------------"
read -p "Enter SMTP host address: " smtp_address
read -p "Enter user email: " email
read -p "Enter port: " port
read -s -p "Enter user password: " password

echo "-------------------"
export EMAIL=$email
export EMAIL_PASSWORD=$password
export HOST_SMTP=$smtp_address
export PORT_SMTP=$port

Next, we are going to run:

rails g mailer SendingNotification

In application_mailer configure email variable app/mailers/application_mailer.rb:

class ApplicationMailer < ActionMailer::Base
  default from: ENV['EMAIL']
  layout "mailer"
end

Also in the file app/mailers/sending_notification_mailer.rb add the following method send_notification:

class SendingNotificationMailer < ActionMailer::Base
  def send_notification(subscriber)
    @subscriber = subscriber

    mail(to: @subscriber.email, subject: "Thanks for subscribing!") do |format|
      format.html { render layout: 'mailer' }
    end
  end
end

In app/views/sending_notification_mailer/send_notification.html.erb add the following html:

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <style>
      /* Add your custom CSS styles here */
    </style>
  </head>
  <body>
    <h1>Thanks for subscribing!</h1>
    <p>Dear <%= @subscriber.name %>,</p>
    <p>Thank you for subscribing to our newsletter. We appreciate your interest in our services.</p>
    <p>Should you have any questions or need further assistance, please feel free to reach out to us.</p>
    <p>Best regards,</p>
    <p>Your Company name here</p>
  </body>
</html>

And finally call mailer from Rails controller app/controllers/subscribers_controller.rb:

class SubscribersController < ApplicationController
  def index
    @subscribers = Subscriber.all
  end
  def new
    @subscriber = Subscriber.new
  end
  def create
    @subscriber = Subscriber.new(subscriber_params)
    if @subscriber.save
      SendingNotificationMailer.send_notification(@subscriber).deliver_now
      puts "Email sent!"
    else
      render :new
    end
  end
  def edit
    @subscriber = Subscriber.find(params[:id])
  end
  def update
    @subscriber = Subscriber.find(params[:id])
    if @subscriber.update(subscriber_params)
      puts "Subscriber updated!"
    else
      render :edit
    end
  end
  def destroy
    @subscriber = Subscriber.find(params[:id])
    @subscriber.destroy
    puts "Subscriber deleted!"
  end
  private
  def subscriber_params
    params.require(:subscriber).permit(:name, :email, :phone, :message)
  end
end

Also we have to generate a model Subscriber with command:

rails generate model Subscriber name:string email:string phone:string message:string

following with:

rake db:migrate
== 20230526105857 CreateSubscribers: migrating ================================
-- create_table(:subscribers)
   -> 0.0007s
== 20230526105857 CreateSubscribers: migrated (0.0007s) =======================