In my Rails 4 application I already store all outgoing emails in DB using an observer. In config/initializers/all_emails_observer.rb I have roughly the following code:
class AllEmailObserver
def self.delivered_email(message)
sent_email = SentEmail.new(
sender: message.from.join(';'),
recipients: message.to,
subject: message.subject
)
sent_email.body = if message.html_part || message.text_part
message.html_part.blank? ? message.text_part.body.raw_source : message.html_part.body.raw_source
else
message.body.raw_source
end
sent_email.save!
end
end
ActionMailer::Base.register_observer(AllEmailObserver)
Now I need to add another feature to let admins re-send any of the emails from the email log.
There are a couple of solutions that I could see right off hand:
- Add code to store all attachments (regular and inline), then implement a method that would generate a new email and re-send it. I'm working on this now.
- Store the mailer class, mailer method and arguments (serialized using GlobalId, for example). When the admin needs to re-send an email - generate a new email from scratch. I don't like this method because ideally I want re-sent emails to have exactly the same content (including attachments) as when they were originally sent. Mailers could have bugs/typos fixed since, but I do want all those bugs and typos to be still there when an email is re-sent.
Now that Rails 4.2 is released and ActiveJob is stable, I didn't find the standard way to do this: all queued emails are immediately deleted after they are sent (I just checked delayed_job backend). There must be a way to maybe preserve a completed mailer job in some separate DB table and then re-queue that job when needed.
I'd love to re-use the email serialization mechanism of ActiveJob to achieve my goal if possible, because I don't want to re-write my observer when Rails 6 is released with a completely changed observer API.
What is the better way to enable re-sending of sent emails?
Please note that I already reviewed similar questions here:
However both of them are about how to store sent emails and not about how to re-send them later as is.
Thank you! Alex.