How We Did Email Newsletters

  • Tutorial
Hello, Habr!

For a long time I was going to write about how we in our company implemented email newsletters, but still did not reach our hands. In general, I do not need to tell you about the benefits of email marketing, I just want to share the technical details of the implementation of this task on Ruby on Rails.


It is necessary that users periodically receive emails under a certain condition. For example: User registered 5 days ago.


Each sent email must be logged in order to know whether we have already sent such and such a letter to such or such a user. First, create the EmailLog model.

rails g model EmailLog user:belongs_to type:string

Next, we describe the notification class that sends messages and writes a log:

app / services / notifications / base.rb

        @user = user
        NotificationMailer.send(notification_type, user).deliver
          type: notification_type

Now we want to send a letter with the content like: “Hey, you registered, but you haven’t bought anything!” 5 days after registration. We need to describe the class of this notification

app / services / notifications / notification / five_days_after_registration.rb

moduleNotificationsmoduleNotificationclassFiveDaysAfterRegistration < Basedefperform?
        user.created_at.to_date == 5.days.ago.to_date && EmailLog.where(log_params).blank?

And here the most interesting thing is that all this must be periodically launched. We need a class that runs through all types of notifications and sends them depending on their conditions. Create a Worker Class

app / services / notifications / worker.rb

    EMAIL_TYPES = %w(
      @user = user
      EMAIL_TYPES.each do|notification_type|
        notification_class = "notifications/notification/#{notification_type}".classify.constantize
        notification =
        if notification.perform?
          puts "Notification «#{notification_type}» was sent to #{}"breakendendendendend

Done. So, to send notifications to the user, you can simply write in the console:!

And all notifications, the conditions of which the current user will satisfy, will be sent.

But we need to do newsletters across the entire user base. The rake task , which we will run every day, for example, at 10 am cron , is perfect for this . For this we need gem whenever .

lib / tasks / notifications.rake

namespace :notificationsdo
  desc 'Lets send emails'
  task send::environmentdo
    User.where(receive_email_notifications:true).each do|user|!

config / schedule.rb

every :day, at:'10:00am'do
  rake 'notifications:send', output:'log/notifications.log'end

Well, that’s it, the newsletter works! If you have questions write comments, if there are no questions, then write comments;)

Also popular now: