How to Send Emails with Ruby on Rails
In order to start with email services in Rails, we need to generate mailer object by running the following Rails command
rails generate mailer Welcome hello
This Rails command line will generate several files in Ruby project for us including
app/mailers/welcome.rb
app/views/welcome/hello.text.erb
app/views/welcome/hello.html.erb
Mail center get a new “Welcome” and it acts as a controller for the web implementation. We are provisioning Welcome mail center that generates “hello” email which is similar to action for the web implementation.
class Welcome < ActionMailer::Base
default from: “test@test.com”
def hello(user, sent_at=Time.now)
@user=user,
@sent_at = sent_at
attachments[“file.txt”] = File.read(“/folder/file.txt”)
mail(subject: “Email Subject”, to: user_email)
end
end
This code sample is designed to send email with subject “Email Subject” to user with email test@test.com with the attachment from the disk.
The file notification.rb is designed to act as a controller and each message has association with a template. It is designed to act in the same way as HTML view. However, views don’t have access to instance variables and must be passed as hashes.
In order to send an email, you need to add the following line to either controller, model or set it up in an observer.
Notificatoin.welcome(user).deliver
ActionMailer can be used for other purposes including error notifications. It’s important to note that Rails provides templating engine out of the box with view of two types:text and html. Both of these views can be found by looking at the files with text.erb and html.erb extensions.