0
0
Ruby on Railsframework~5 mins

Sending emails from controllers in Ruby on Rails

Choose your learning style9 modes available
Introduction

Sending emails from controllers lets your app notify users right after they do something, like signing up or ordering.

After a user signs up, send a welcome email.
When a user resets their password, send a reset link.
Notify admins when a new order is placed.
Send confirmation emails after a form submission.
Syntax
Ruby on Rails
UserMailer.welcome_email(@user).deliver_now
Use deliver_now to send the email immediately.
You call the mailer method with the data it needs, like a user object.
Examples
Sends the welcome email right away.
Ruby on Rails
UserMailer.welcome_email(@user).deliver_now
Sends the reset password email later using background jobs.
Ruby on Rails
UserMailer.reset_password_email(@user).deliver_later
Immediately notifies admins about a new order.
Ruby on Rails
AdminMailer.new_order_notification(order).deliver_now
Sample Program

This controller creates a user and sends a welcome email immediately after saving. The mailer defines the email details.

Ruby on Rails
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.welcome_email(@user).deliver_now
      redirect_to root_path, notice: "Welcome email sent!"
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
end

class UserMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: "Welcome to Our App")
  end
end
OutputSuccess
Important Notes

Use deliver_later to send emails asynchronously and avoid slowing down user actions.

Keep email sending logic in mailers, not controllers, for cleaner code.

Always test emails in development using tools like Letter Opener or Mailcatcher.

Summary

Controllers trigger emails by calling mailer methods with data.

Use deliver_now for immediate sending, deliver_later for background jobs.

Keep email content and setup inside mailers, not controllers.