0
0
Ruby on Railsframework~5 mins

Action Mailer setup in Ruby on Rails

Choose your learning style9 modes available
Introduction

Action Mailer helps your Rails app send emails easily. It organizes email sending like writing and sending letters.

Send welcome emails when users sign up.
Notify users about password changes.
Send order confirmations in an online store.
Deliver newsletters or updates to subscribers.
Syntax
Ruby on Rails
class UserMailer < ApplicationMailer
  default from: 'notifications@example.com'

  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end

Define a mailer class inheriting from ApplicationMailer.

Use mail method to set recipient and subject.

Examples
A simple mailer method sending an alert email.
Ruby on Rails
class NotificationMailer < ApplicationMailer
  def alert_email(user)
    mail(to: user.email, subject: 'Alert!')
  end
end
Sets a default sender email for all mails in this mailer.
Ruby on Rails
class UserMailer < ApplicationMailer
  default from: 'support@example.com'

  def reset_password_email(user)
    @user = user
    mail(to: @user.email, subject: 'Reset your password')
  end
end
Sample Program

This example shows how to set up SMTP settings in development, create a mailer, and send a welcome email immediately.

Ruby on Rails
# config/environments/development.rb
Rails.application.configure do
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: 'smtp.example.com',
    port: 587,
    user_name: 'user@example.com',
    password: 'password',
    authentication: :plain,
    enable_starttls_auto: true
  }
end

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  default from: 'notifications@example.com'

  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end

# Usage in Rails console or controller
user = OpenStruct.new(email: 'newuser@example.com')
email = UserMailer.welcome_email(user)
email.deliver_now

puts "Email sent to: #{email.to.first} with subject: '#{email.subject}'"
OutputSuccess
Important Notes

Remember to configure SMTP settings for your environment to send emails.

Use deliver_now to send immediately or deliver_later to send asynchronously.

Test emails in development with tools like Letter Opener or Mailcatcher to avoid sending real emails.

Summary

Action Mailer organizes email sending in Rails apps.

Define mailer classes and methods to create emails.

Configure SMTP settings to send emails through a mail server.