Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse email string to data structure in Clojure

Tags:

email

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.

like image 921
Honza Pokorny Avatar asked Apr 08 '26 08:04

Honza Pokorny


1 Answers

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)))
like image 88
Honza Pokorny Avatar answered Apr 11 '26 14:04

Honza Pokorny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!