   (.sendToAdmins (get-mail-service) (make-mail-service-message msg)))
 
 
+(defrecord #^{:private true} MessageAlternativeParts [parts])
+(defrecord #^{:private true} MessagePart [filename content-type data])
+
+
+(defn- deconstruct-message [#^MimeMessage message]
+  (let [all-subparts (fn [part]
+                       (map #(.getBodyPart part %) (range (.getCount part))))
+        subparts (fn subparts [part]
+                   (let [content-type (.toLowerCase (.getContentType part))]
+                     (cond
+                      ;; multiple attachments
+                      (re-matches #"multipart\/mixed.*" content-type)
+                      (doall (map subparts (all-subparts (.getContent part))))
+                      ;; probably message text
+                      (re-matches #"multipart\/alternative.*" content-type)
+                      (MessageAlternativeParts.
+                       (doall (map subparts (all-subparts (.getContent part)))))
+                      ;; a specific attachment
+                      :else (let [content (.getContent part)]
+                              (if (string? content)
+                                  (MessagePart. (.getFileName part) content-type content)
+                                  (with-open [tempout (java.io.ByteArrayOutputStream.)]
+                                    (copy-stream (.getInputStream part) tempout)
+                                    (MessagePart. (.getFileName part) content-type
+                                                  (.toByteArray tempout))))))))]
+    (flatten [(subparts message)])))
+
+
 (defn parse-message [request]
   (let [session (javax.mail.Session/getDefaultInstance (java.util.Properties.) nil)
         raw-msg (javax.mail.internet.MimeMessage. session (.getInputStream (:request request)))

        to (map #(.toString %) (.getRecipients raw-msg javax.mail.Message$RecipientType/TO))
        cc (map #(.toString %) (.getRecipients raw-msg javax.mail.Message$RecipientType/CC))
        reply-to (first (map #(.toString %) (.getReplyTo raw-msg)))
        message-id (.getMessageID raw-msg)]
    (record MailMessage
            :from from :to to :subject subject
            :reply-to reply-to :cc cc)))

(ns appengine-magic.services.mail
  (:refer-clojure :exclude (send))
  (:use [appengine-magic.utils :only [record copy-stream]])
  (:import [com.google.appengine.api.mail MailServiceFactory
            MailService$Message MailService$Attachment]))

