Creating Rake Task for Sending Notification Emails
​In this guide you'll learn how to create rake task in Rails for sending email notifications.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this video, we're going to take care of the rake task that'll send out emails.

Go to lib/tasks and here, you can see a file called notification.rake. This file already has the SMS functionality set up, and we can duplicate it for email too. We have to change the description as well as the name of the task.

# lib/tasks/notification.rake

desc "Sends mail notification to managers (admin users) each day to inform of pending overtime requests"
task manager_email: :environment do

end

Now, run bundle exec rake -T, and you should be able to see it in the task list. We can even take it one step further and print out a message.

# lib/tasks/notification.rake

desc "Sends mail notification to managers (admin users) each day to inform of pending overtime requests"
task manager_email: :environment do
  puts "I'm in the manager email"
end

Run this specific task now, with the command bundle exec rake notification:manager_email and it prints out our message.

large

Now, we'll add the functionality. We have to
1. Iterate over the overtime requests that have a status of "submitted".
2. Check to see if there are any requests
3. Iterate over the list of admin users/managers
4. Send email to each admin

It's pretty straightforward, so I like to run them through the console first. Let's get a list of posts with the "submitted" status with the code:

submitted_posts = Post.submitted

Next, we'll say that if the count is greater than zero, then just print something

if submitted_posts.count > 0
  puts "asdf"
end

That prints out the value, so we have access to it.

We are going to paste this in our file, and inside the conditional, we'll iterate over the list of admin users and send an email to each of them.

# lib/tasks/notification.rake

desc "Sends mail notification to managers (admin users) each day to inform of pending overtime requests"
task manager_email: :environment do
  submitted_posts = Post.submitted
  admin_users = AdminUser.all

  if submitted_posts.count > 0
    admin_users.each do |admin|
      ManagerMailer.email(admin).deliver_now
    end
  end
end

Start the server, open another terminal window and type rake notification:manager_email. Depending on your environment configuration, this will either work or it may throw a mailer connection error.

devCamp Note: When we deploy to the web you'll see that the email functionality is working properly.

Resources