title: Rails 4.2 - Send Image Data as Email Attachment Without Saving Image
body: <p>My client app is an iOS app written in Swift. In that iOS app, I convert an image to a Base64 encoded String and then send this String to my Rails server in the body of an HTTP request. This is my code for doing so:</p>
  
  <pre><code>// Create a new URL request with the URL
  let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
  
  // Set the HTTP method to POST
  request.HTTPMethod = "POST"
  
  // Set the content type of the request to XML
  request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
  
  // Convert the image to binary and then to a Base 64 Encoded String
  let imageData:String = UIImagePNGRepresentation(image).base64EncodedStringWithOptions(nil)
  
  // Set the HTTP Body of the request to the image
  request.HTTPBody = NSData(base64EncodedString: imageData, options: nil)
  </code></pre>
  
  <p>In my Rails controller handling the request, I would like to retrieve the image and send it as an email attachment. I do NOT want to save the image anywhere; I just want to decode the image in memory and then somehow use that as the email attachment.</p>
  
  <p>How can I retrieve the image data in my Rails controller and decode it in a way that would allow me to send it back as an email attachment?</p>
  
  <p>To retrieve the image data, I've tried using <code>request.body.read</code>, but this returns an empty String for some reason.</p>
  
  <p>Thanks in advance for any help!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p><code>request.body.read</code> was returning an empty String because I used a GET request. I've since learned that it's not a good idea to send an HTTP Body in a GET request, so I changed the method to POST. Now <code>request.body.read</code> is returning my encoded String! I've also added the Content-Type header to the request.</p>
  
  <p>Still, I can't figure out how to properly decode the HTTP Body and assign it to an image object of some sort.</p>
  
  <p><strong>EDIT #2:</strong></p>
  
  <p>I've managed to send the email attachment in my mailer using the following code:</p>
  
  <pre><code>attachments["file.png"] =
  {
     mime_type: 'image/png',
     content: Base64.decode64(request.body.read)
  }
  </code></pre>
  
  <p>Unfortunately, the PNG file cannot be opened when I receive it in the email. I don't know if the encoding translates well from Swift to Ruby. I'll keep investigating.</p>
  
  <p><strong>EDIT #3:</strong></p>
  
  <p>I removed the Base64 String encoding, and it's working great! See my posted answer below.</p>