How do I get ActionMailer to log sent messages but NOT include the attachments?

actionmailer, logging, ruby-on-rails, ruby-on-rails-3.2

Solution

I ended up having it log the following details about each mail that gets sent out:

- The headers

- The structure of the email (which parts are within which other parts), including a list of attachments, before stripping out all attachments

- Decoded, human-readable, searchable message bodies (the Rails default is to log the encoded, which is hard for a human to read and breaks words in random places, making it hard to search)

To accomplish this, I overrode `ActionMailer::Base.set_payload_for_mail` in my app and replaced this line:

payload[:mail]       = mail.encoded

with a version that:

- Creates a copy of the Mail object

- Calls `mail.without_attachments!`, and

Only logs:

- `mail.header.encoded`

- the output from `mail.inspect_structure` (from my fork)

- the result of calling `part.decoded` for each (non-attachment) part.

Check out this gist for the whole thing.

Problem

I like that Rails automatically logs all messages that are sent out from the app. What I don't like is how it fills up my log file with huge blocks of useless Base64-encoded text. This makes looking through the log file a pain because I have to skip past these megabytes-long blocks of unreadable noise. It also causes the log file to grow too quickly and fill up the disk. How can I get it to still log all messages that are sent but NOT include any of the attachments? Is there a way to tell it to strip out the attachments before logging or something? Usually all I'm interested in seeing are the headers (subject, who it was sent to) and (at least some of the time) the message body text. It wouldn't hurt to also have a list of the attachments (file name and type) too — but it certainly does me no good to see the full Base64 dump of all the attachments! (If I want to check and see if the attachments are coming through okay, I already know how to add a mail interceptor that bcc's all outgoing mail to my inbox.)

Original source