3

I'm looking for a way to take an email message in plain text and parse it into something nicer for use in a Clojure project. The resulting data structure should allow me to quickly get the sender, subject, body and attachments.

There is a similar question to this but in Java:

Java Email message Parser?

Most libraries I found only support email sending and not necessarily parsing.

Community
  • 1
  • 1
Honza Pokorny
  • 3,205
  • 5
  • 37
  • 43
  • 2
    use javax.mail, http://stackoverflow.com/questions/3444660/java-email-message-parser is answer. – number23_cn Jun 29 '12 at 14:38
  • Could you give me an example of how to do that in a proper answer? – Honza Pokorny Jun 29 '12 at 14:51
  • 2
    If you already have an example of how to do it in Java, my first instinct would be to use Java interop to do the parsing and then `clojure.core/bean` to turn it into a Clojure structure. – Alex Jun 29 '12 at 14:55

1 Answers1

4

Since nobody answered, maybe I should. Here is a very simple example of loading an email file and printing out the from field (first address).

(ns something.views.welcome
  (:use [noir.core :only [defpage]]
        [clojure.contrib.java-utils]
        [clojure.java.io :only [input-stream]])
(:import 
    (javax.mail Session)
    (javax.mail.internet MimeMessage)
))


(def session
    (Session/getDefaultInstance 
    (as-properties [["mail.store.protocol" "imaps"]])))


(def email "email.txt")

(defn get-message [filename]
    (bean (MimeMessage. session (input-stream filename))))

(defn get-from [message]
    (.toString (first (:from message))))



(println (get-from (get-message email)))
Honza Pokorny
  • 3,205
  • 5
  • 37
  • 43