Search code examples
ruby-on-railsrubyemailattachmenttemporary-files

Errors Attaching Tempfile to Email in Rails


Have file in @attachment. From debug:

"datafile"=>#<ActionDispatch::Http::UploadedFile:0x3eee9c0        @original_filename="filename.jpg",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"datafile\";   filename=\"filename.jpg\"\r\nContent-Type: image/jpeg\r\n",
 @tempfile=#<File:C:/Users/.../RackMultipart20121026-2452-g369hf>>,

It was uploaded via a user form.

I'm trying to attach it to an email:

...
attachments[@attachment.original_filename] = @attachment
mail(:to => "[email protected]", :subject => "test", :from => @fromaddress)

Which errors:

undefined method `length' for #

I have also tried

attachments[@attachment.original_filename] = @attachment.tempfile

Which errors:

undefined method `[]' for #<Tempfile:0x5629e48>

@attachment.original_filename returns the proper filename ("filename.jpg" in example)

Anything obvious?


Solution

  • Unless you save the uploaded file to some place, it's a bit limited, what you can do with it (for security reasons - you are supposed to validate the upload and then store the file).

    But you should be able to read the file:

    attachments[@attachment.original_filename] = @attachment.read
    

    Note: I haven't tested this, maybe you need to read from the @attachment.tempfile