Best way to log ActionMailer sent emails in a database?
I need to log emails sent through ActionMailer and a simple text file isn't enough. I'd need to store the logs in an ActiveRecord model. Email sending performance will likely take a hit, but in this case, it's the best alternative (since the logs are afterwards routinely accessed by the app).
I'd also need to log what was actually sent and the errors associated, not just what my controller passes to ActionMailer (ie. the lowest level implementation possible).
config.action_mailer开发者_开发知识库.logger
seems an ideal way to hijack the machinery already in place by Rails to do so. However, from my understanding, Log4r and the default Ruby logger can only output to text files.
Any suggestions?
Thanks!
There are 2 ways to solve your problem, since you want to store the contents of the mail as well.
Before that, the typical contents of a mail are:
Sent mail to 123@gmail.com
From: abc@xyz.com
To: 123@gmail.com
Subject: Blah
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Hi, yourself.
These are outlined as follows
Storing the mails in the database can be done on a periodical basis(say an hour, a day or a week) depending on the way you want it. This way you can run it as a background job, which will look up the log file and extract the contents that you want.
A much better way of doing the same could be, that you attach a callback function to the mailing function, so that whenever you send a mail i.e. you call the deliver function, your callback function gets called on its own, looks up the log from the tail end to a certain point and then extracts the content and then stores it in the same.
The callback function can be a simple ruby script, that opens the log and reads its contents and then you can play around with it and store it in the way you want.
精彩评论