 
 
 (defn make-attachment [filename data]
-  (MailService$Attachment. filename data))
+  (MailService$Attachment. filename (if (instance? (class (.getBytes "")) data)
+                                        data
+                                        (.getBytes data))))
 
 
 (defn make-message [& {:keys [from to subject text-body html-body

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


        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)
        msg-raw-parts (deconstruct-message raw-msg)
        msg-parts (reduce (fn breakdown [acc raw-part]
                            (cond
                             ;; alternatives
                             (instance? MessageAlternativeParts raw-part)
                             (reduce breakdown acc (:parts raw-part))
                             ;; has a valid filename, must be an attachment
                             (not (nil? (:filename raw-part)))
                             (assoc acc :attachments
                                    (conj (:attachments acc)
                                          (make-attachment (:filename raw-part)
                                                           (:data raw-part))))
                             ;; text part
                             (re-matches #"text\/plain.*" (:content-type raw-part))
                             (assoc acc :text-body (:data raw-part))
                             ;; HTML part
                             (re-matches #"text\/html.*" (:content-type raw-part))
                             (assoc acc :html-body (:data raw-part))))
                          {:attachments []}
                          msg-raw-parts)]
    (record MailMessage
            :from from :to to :subject subject
            :reply-to reply-to :cc cc
            :text-body (:text-body msg-parts) :html-body (:html-body msg-parts)
            :attachments (:attachments msg-parts)
            :message-id message-id)))
