ruby 的邮件 gem:如何查看附件是否内联

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

比如说,我在文件中有一封原始邮件消息,我读起来像

m = Mail.read '/path/to/file'

它有附件,其中一个是内联图片。

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>>>

其他的只是一些文件。

我需要的 是知道附件是否内嵌的方法。有一个 inline? 方法,对于非内联附件,它就像一个魅力

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

但让我们 return 到我们的 pic 这里:

pic.inline?
=> nil

这是不对的。我也试过

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

pic['Content-Disposition']
=> nil

也不太好

这里有什么方法可以得到true/false值吗?

对于您的情况,图片没有定义 Content-Disposition header。标准之间的差异略有不同(有些默认为 attachment,有些默认为 inline)。引用 RFC 2183:

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

mail gem 似乎默认为 attachment,因为它只检查 Content-Disposition 是否明确设置为 inline

如果您想默认为 inline,您可以检查 inline? 方法的结果是否 returns 除了 false.

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

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

最后,这取决于定义的语义,您必须相当小心,因为这些东西往往被不同的人解释不同。当您接受来自未知来源的邮件时,您可以检查邮件 body 中是否以某种方式引用了没有显式 Content-Disposition 的附件。