Rails : Sending Email As Background Job

Submitted by swarut on Fri, 10/26/2012 - 16:32

In rails, the normal mail sending task via Mailer is asynchronus. Thus, in the mailer method, we pass the id of the model instead of the model itself because the life time of the model may be ended before the mail sending task is started. 

However, for the background job, the mail sending task should not be done asynchronusly. We run the background job, and mail sending is also a background job. This mean we can run both of them together. We can also have the model entity available at running time.

The below codes show the different implementation of mail sending method in asynchronus and synchronus manner respectively.

  1.   def mentoring_survey(pending_survey_id)
  2.     @pending_survey = Survey.find(pending_survey_id)
  3.     @user = @pending_survey.user
  4.  
  5.     sendgrid_category "Mentoring Survey Notification"
  6.  
  7.     subject = t('survey_mailer.mentoring_survey.subject')
  8.  
  9.     mail(to: @user.email, subject: subject) do |format|
  10.       format.text
  11.       format.html { render layout: 'mailer' }
  12.     end
  13.   end

  1.   def mentoring_survey_reminder(pending_survey)
  2.     @pending_survey = pending_survey
  3.     @user           = pending_survey.user
  4.  
  5.     sendgrid_category "Mentoring Survey Reminder"
  6.  
  7.     subject = t('survey_mailer.mentoring_survey_reminder.subject')
  8.  
  9.     mail(to: @user.email, subject: subject) do |format|
  10.       format.text
  11.       format.html { render layout: 'mailer' }
  12.     end
  13.   end