Search code examples
ruby-on-railsrubyexchangewebservicesrest-clientviewpoint

How to relay EWS email attachments to a REST endpoint using Viewpoint


I need to forward an Outlook EWS email and its attachments to a Rails server.

The attachments I am getting with the Viewpoint gem are returned as Viewpoint::EWS::Types::FileAttachment objects.

How can I pass these attachments to a Rails server using the rest-client library?


Solution

  • I managed to upload the files by using a StringIO and giving it a :path

    # email is a Viewpoint::EWS::Types::Message
    # email_endpoint is a RestClient::Resource
    
    attachments = email.attachments.map do |attachment|
      file = StringIO.new(Base64.decode64(attachment.content))
      file.class.class_eval { attr_accessor :original_filename, :content_type, :path }
      file.original_filename = attachment.file_name
      file.content_type = attachment.content_type
      file
    end
    
    response = email_endpoint.post(
      email: {
        subject: email.subject,
        attachments: attachments
      }
    )
    

    The rest-client library will automatically handle objects that respond to :path and :read as Files and use a multi-part upload.

    Each attachment then shows up in Rails as an ActionDispatch::Http::UploadedFile with the correct filename.