Honza Pokorny
Honza Pokorny

Reputation: 3235

Parse email string to data structure in Clojure

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.

Upvotes: 3

Views: 964

Answers (1)

Honza Pokorny
Honza Pokorny

Reputation: 3235

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)))

Upvotes: 4

Related Questions