Rails 3使用Apple Mail.app中的附件阅读电子邮件

时间:2012-04-02 15:44:59

标签: ruby-on-rails ruby ruby-on-rails-3.1 actionmailer

我正在使用cloudmailin接收发送到特定地址的电子邮件。我正在尝试一个简单的场景,我发送一封包含Mail.app附件的电子邮件。当我在我的应用程序中收到帖子时,我创建了一个邮件对象。

创建邮件对象时,附件为空。

mail_str = 
"Received: (qmail 16453 invoked from network); 2 Apr 2012 14:27:29 -0000\r\nReceived: from unknown (71.170.102.226)\r\n  by smtpauth20.prod.mesa1.secureserver.net (64.202.165.36) with ESMTP; 02 Apr 2012 14:27:29 -0000\r\nFrom: Jake Dempsey <jake@direct2mfg.com>\r\nContent-Type: multipart/mixed; boundary=\"Apple-Mail=_8E1F0992-1DAA-409B-BC73-74747FFDFA98\"\r\nSubject: inv\r\nDate: Mon, 2 Apr 2012 09:27:28 -0500\r\nMessage-Id: <EB899F47-7E1F-4853-AE17-17290BF7B4F8@direct2mfg.com>\r\nTo: 4511bea79e86da90d6d2@cloudmailin.net\r\nMime-Version: 1.0 (Apple Message framework v1257)\r\nX-Mailer: Apple Mail (2.1257)\r\n\r\n\r\n--Apple-Mail=_8E1F0992-1DAA-409B-BC73-74747FFDFA98\r\nContent-Disposition: attachment;\r\nfilename=test.csv\r\nContent-Type: text/csv;\r\nname=\"test.csv\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nRemove Itesm,Item ID,Short Desc,Long Desc,Segment,Item =\r\nClass,Cost,MSRP,Stock UOM, Unit Vol,Unit Weight,Unit Height,Unit =\r\nLength,Unit Width=0Dno,1, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,2, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,3, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,4, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,5, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,6, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,7, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0Dno,8, super short, super long long, Casual, =\r\nCasual,1,3,Each, , , , , =0D=\r\n\r\n--Apple-Mail=_8E1F0992-1DAA-409B-BC73-74747FFDFA98--\r\n"

mail_obj = Mail.new mail_str
puts mail_obj.attachments.size #should be 1

如果我通过其他客户发送电子邮件,我可以创建mail_obj,附件大小为1.

我正在使用rails 3.1.3

1 个答案:

答案 0 :(得分:1)

我们遇到一些问题,邮件宝石总是找到正确的附件和查找嵌套附件。最后,我们最终创建了一个迭代每个消息部分并递归提取任何附件的方法。

例如

(警告这不是我们使用的实际方法,因此可能不完美)

def parse_attachment(mail, attachments=[])
  mail.parts.each do |part|
    if part.attachment?
      attachments << part
    else
      if part.parts && part.parts.length > 0
        parse_attachment(part, attachments)
      end
    end
  end
  return attachments
end