How to Send email in Ruby on Rails

Step- 1 Generate a mailer class by using command

rails g mailer icd_code

  • This will create the IcdCodeMailer class inside the mailer folder of app.

*suppose we want to send mail when any new icd_code generate*



Step-2 In this case we will create a callback in icd_code mode....

after_create :send_notification_email

def send_notification_email
SendEmailForNewIcdCodeWorker.perform_at(1.minutes.from_now, self.id)
end

**In this method SendEmailForNewIcdCodeWorker is a worker which is called after create a new icd_code**

Step-3

Inside worker folder create a worker for SendEmailForNewIcdCodeWorker. Which will look like this...

class SendEmailForNewIcdCodeWorker
include Sidekiq::Worker
def perform(icd_id)
IcdCodeMailer.send_email_for_new_icd_code(IcdCode.where(id: icd_id).first)
end
end

save it as followed.... send_email_for_new_icd_code_worker.rb

step-4

Inside IcddCodeMailer create a method

def send_email_for_new_icd_code(icd_code)
@icd_code = icd_code
mail({
to: APP_CONFIG['notify_email'],
subject: "New IcdCode has been added - (#{ Rails.env })"
}).deliver
end


step-5

Create a view template of email.

Inside view->icd_code_mailer

<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<p>Hello</p>

<p>There has been a new Icd_code submission through the CompCorePro website. Below are the details:</p>

<p><b>Name</b> : <%= @icd_code.name %></p>
<p><b>ICD 10 CODE</b> : <%= @icd_code.icd10 %></p>
<p><b>DESCRIPTION.</b> : <%= @icd_code.description %></p>
<p><b>OFF WORK</b> : <%= @icd_code.off_work %></p>
<p><b>LIGHT DUTY</b> : <%= @icd_code.light_duty %></p><br/>

Thank you,<br>
CompCorePro
</body>
</html>


save it as follow send_email_for_new_icd_code.html.erb

Step-6

Set the configration inside config->environment-> Production

Copy paste code from git_hub.


Comments