Calling a mailer from a different mailer

627 Views Asked by At

I want a mailer class (let's say UserMailer) to call a method on another mailer class (let's say LoggerMailer) when UserMailer's method is called. My code is like this:

app/mailers/logger_mailer.rb

class LoggerMailer < ActionMailer::Base
  def log_mail(...)
    ...
    mail(layout: ..., template: ..., to: ..., from: ..., subject: ..., ...)
  end
end

app/mailers/user_mailer.rb

class UserMailer < ActionMailer::Base
  def some_mail_method(...)
    ...
    LoggerMailer.log_mail(...)
    mail(layout: ..., to: ..., from: ..., subject: ..., ...)
  end
end

UserMailer#some_mail_method is the main mail method, and when this is called, I want it to call LoggerMailer#log_mail in addition to its own mail method call.

However, when I call UserMailer#some_mail_method, it does not seem to call LoggerMailer#log_mail. I feel so because when I put a line binding.pry within the method body of LoggerMailer#log_mail, it does not seem to stop at that point.

  1. Is LoggerMailer.log_mail actually called?
  2. In general, is it possible or not to call a mailer method from the method body of another mailer method?
1

There are 1 best solutions below

0
On BEST ANSWER

Your problem is that mailer methods don't send anything on their own, they (by calling mail) just return ActionMailer::MessageDelivery instances and then someone calls deliver_now or deliver_later on that ActionMailer::MessageDelivery to actually arrange delivery.

When you do this:

LoggerMailer.log_mail(...)

you're calling the mailer but throwing away the ActionMailer::MessageDelivery that it returns so nothing useful happens.

You need to deliver the log mail:

LoggerMailer.log_mail(...).deliver_now

You could also put the LoggerMailer.log_mail and UserMailer. some_mail_method messages in a wrapper that would forward the deliver_now or deliver_later methods when the caller gets around to trying to deliver the some_mail_method.