title: Why do I get a string encoding issue "\xE2" from ASCII-8BIT to UTF-8?
body: <p>I'm trying to download a PDF from an email and write the contents to a file. For some reason, I'm getting this error:</p>
  
  <pre><code>An Encoding::UndefinedConversionError occurred in attachments#inbound: "\xE2" from ASCII-8BIT to UTF-8 app/controllers/api/attachments_controller.rb:70:in `write'
  </code></pre>
  
  <p>Here's my code:</p>
  
  <pre><code>def inbound
      if Rails.env.production? or Rails.env.staging?
        email = Postmark::Mitt.new(request.body.read)
      else
        email = Postmark::Mitt.new(File.binread "#{Rails.root}/app/temp_pdfs/email.json")
      end
  
      if email.attachments.count == 0
        # notify aidin that we got an inbound email with no attachments
        respond_to do |format|
          format.json { head :no_content }
        end
        return
      end
      attachment = email.attachments.first
      filename = "attachment" + (Time.now.strftime("%Y%m%d%H%M%S")+(rand * 1000000).round.to_s) + ".pdf"
      base_path = "#{Rails.root}/temp_attachments/"
      unless File.directory?(base_path)
        Dir::mkdir(base_path)
      end
      file = File.new base_path + filename, 'w+'
      file.write Base64.decode64(attachment.source['Content'].encode("UTF-16BE", :invalid=&gt;:replace, :replace=&gt;"?").encode("UTF-8"))
      file.close
      write_options = write_options()
      write_options[:metadata] = {:filename =&gt; attachment.file_name, :content_type =&gt; attachment.content_type, :size =&gt; attachment.size }
  
      obj = s3_object()
      file = File.open file.path
      obj.write(file.read, write_options)
      file.close
  
      FaxAttach.trigger obj.key.split('/').last
  
      render :nothing =&gt; true, :status =&gt; 202 and return
    end
  </code></pre>
  
  <p>I read around and it looked like the way to solve this was:</p>
  
  <pre><code>file.write Base64.decode64(attachment.source['Content'].encode("UTF-16BE", :invalid=&gt;:replace, :replace=&gt;"?").encode("UTF-8"))
  </code></pre>
  
  <p>but it doesn't seem to work.</p>