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.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…