Stepan Salin Stepan Salin - 1 year ago 84
Ruby Question

ruby's Mail gem: how to see if attachment is inline

Say, i have a raw mail message in a file and i read it like

m = '/path/to/file'

it has attachments, one of which is an inline pic.

pic = m.attachments[0]
=> #<Mail::Part:70130030888740, Multipart: false, Headers: <Content-Type: image/png; name="image001.png">, <Content-Transfer-Encoding: base64>, <Content-ID: <image001.png@01D21F1C.E063ADE0>>>

others are just some files.

What i need is to have a way of knowing whether the attachment is inline or not. There is an
method, and for non-inline attachments it works like a charm

pdf = m.attachments[1]
=> #<Mail::Part:70130031002140, Multipart: false, Headers: <Content-Type: application/pdf; name="blah blah blah blah
=> false

But let's return to our

=> nil

Which is just not right. I also tried

=> #<Mail::Field 0x7f90d729b598 @charset="UTF-8" @name="Content-Disposition" @raw_value="Content-Disposition: attachment;\r\n\tfilename


=> nil

which is not too good either.

Is there any way to have a true/false value here?

Answer Source

In your case, the picture doesn't have a Content-Disposition header. What to make of this differs a bit between standards (some default to attachment, some to inline). So quote RFC 2183:

Content-Disposition is an optional header field. In its absence, the MUA may use whatever presentation method it deems suitable.

The mail gem seems to prefer the default to be attachment since it inly checks if the Content-Disposition was explicitly set to inline.

If you want to default to inline, you can check if the result of the inline? method returns anything else but false.

pic_is_inline = (pic.inline? != false) # pic.inline? returns nil
# => true

pdf_is_inline = (pdf.inline? != false) # pdf.inline? returns false
# => false

In the end, it's up to little defined semantics and you will have to be rather careful since these things tend to be interpreted differently by different people. When you accept mail from unknown sources, you could e.g. check if an attachment without an explicit Content-Disposition is referenced in the body somehow.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download