Jake Dempsey
Jake Dempsey

Reputation: 6312

Rails 3 reading emails with attachments from Apple Mail.app

I am using cloudmailin to receive emails that are sent to a specific address. I am trying a simple scenario where I send an email with an attachment from Mail.app. When I receive the post in my application I create a mail object.

When I create the mail object, the attachments are empty.

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 <[email protected]>\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: <[email protected]>\r\nTo: [email protected]\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

If I send an email through other clients, I am able to create a mail_obj and the attachments size is 1.

I am using rails 3.1.3

Upvotes: 0

Views: 434

Answers (1)

Steve Smith
Steve Smith

Reputation: 5201

We had some issues with the mail gem always finding the correct attachments and finding nested attachments. In the end we ended up creating a method to iterate through each of the message parts and recursively extract any attachments.

for example (warning this isn't the actual method that we used so it might not be perfect)

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

Upvotes: 1

Related Questions