Action mailer

Action Mailer is a feature in Ruby on Rails that allows you to send emails from your application. It provides a way to define email templates and send them to users, administrators, or other stakeholders.

Here are the key concepts and benefits of using Action Mailer:

Key Concepts:

  1. Mailers: A mailer is a class that inherits from ActionMailer::Base. It defines the email templates and the logic for sending emails.
  2. Email Templates: Email templates are HTML or text files that define the content of the email. They can include dynamic data from your application.
  3. Deliveries: Deliveries are the actual emails that are sent to users. You can customize the delivery process by overriding the deliver method.

Benefits:

  1. Separation of Concerns: Action Mailer separates the email sending logic from the rest of your application, making it easier to maintain and test.
  2. Reusability: You can reuse email templates and mailers across multiple controllers and actions.
  3. Flexibility: Action Mailer provides a lot of flexibility in terms of customizing the email sending process, including the ability to override the deliver method.
  4. Testing: Action Mailer provides built-in support for testing email deliveries, making it easier to test your email sending logic.

How to Use Action Mailer:

  1. Create a new mailer class by running the command rails generate mailer MyMailer.
  2. Define the email templates in the app/views/mailer directory.
  3. Define the mailer methods in the app/mailers/mailer.rb file.
  4. Use the mailer methods in your controllers to send emails.

Here is an example of a simple mailer:

# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  default from: '[email protected]'

  def welcome_email(user)
    @user = user
    mail to: user.email, subject: 'Welcome to our application!'
  end
end
# app/views/user_mailer/welcome_email.html.erb
<h1>Welcome to our application, <%= @user.name %>!</h1>
<p>Thank you for signing up.</p>
# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.welcome_email(@user).deliver_now
      redirect_to root_url, notice: 'User created successfully.'
    else
      render :new
    end
  end
end

In this example, the UserMailer class defines a welcome_email method that sends an email to the user with a welcome message. The email template is defined in app/views/user_mailer/welcome_email.html.erb. The UsersController uses the welcome_email method to send an email to the user when they create a new account.