0
0
Ruby on Railsframework~5 mins

Mailer generation and templates in Ruby on Rails

Choose your learning style9 modes available
Introduction

Mailers help your app send emails automatically. Templates let you design what those emails look like.

Send a welcome email when a user signs up.
Notify users about password changes.
Send order confirmations after a purchase.
Alert admins about important events.
Send newsletters or updates to users.
Syntax
Ruby on Rails
rails generate mailer MailerName method_name

# Example:
rails generate mailer UserMailer welcome_email
The command creates a mailer class and email templates.
Mailer methods define what emails to send and what data to include.
Examples
This mailer sends a welcome email to a user.
Ruby on Rails
class UserMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome!')
  end
end
This is the HTML email template that uses the user name.
Ruby on Rails
# Template: app/views/user_mailer/welcome_email.html.erb
<h1>Hello, <%= @user.name %>!</h1>
<p>Thanks for joining us.</p>
This is the plain text version of the email for simpler email clients.
Ruby on Rails
# Template: app/views/user_mailer/welcome_email.text.erb
Hello, <%= @user.name %>!
Thanks for joining us.
Sample Program

This example shows a mailer sending a welcome email to a user named Alice. It prints the recipient, subject, and email body.

Ruby on Rails
class UserMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome to Our App')
  end
end

# Template: app/views/user_mailer/welcome_email.html.erb
# <h1>Welcome, <%= @user.name %>!</h1>
# <p>We are happy you joined.</p>

# Usage in controller or console:
user = OpenStruct.new(name: 'Alice', email: 'alice@example.com')
email = UserMailer.welcome_email(user)
puts email.to
puts email.subject
puts email.body.encoded
OutputSuccess
Important Notes

Always create both HTML and plain text templates for better email compatibility.

Use instance variables (like @user) to pass data to templates.

Test emails in development using tools like Letter Opener or Mailcatcher.

Summary

Mailers send emails from your Rails app.

Templates define how emails look in HTML and text.

Generate mailers with Rails commands and customize methods and views.