POP3 Gmail access with Clojure and JavaMail
2011-05-25I recently had the need to access gmail using Clojure. I used JavaMail to accomplish this via pop3. Below is some code that I wrote to help me get emails. Hope you find it useful Enjoy 🙂
(use '[clojure.contrib.duck-streams])
(def props (System/getProperties))
; Get the default Session object.
(def session (javax.mail.Session/getDefaultInstance props))
; Get a Store object that implements the specified protocol.
(def store (.getStore session "pop3s"))
;Connect to the current host using the specified username and password.
(.connect store "pop.gmail.com" "[email protected]" "password")
;Create a Folder object corresponding to the given name.
(def folder (. store getFolder "inbox"))
; Open the Folder.
(.open folder (javax.mail.Folder/READ_ONLY ))
; Get the messages from the server
(def messages (.getMessages folder))
(defn getFrom [message](javax.mail.internet.InternetAddress/toString (.getFrom message)))
(defn getReplyTo [message] (javax.mail.internet.InternetAddress/toString (.getReplyTo message)) )
(defn getSubject [message] (.getSubject message))
;print out the body of the message
(for [m messages] (read-lines(.getInputStream m)) )
;;;;;code for sending an email
(def props (System/getProperties))
(. props put "mail.smtp.host", "smtp.gmail.com")
(. props put "mail.smtp.port", "465")
(. props put "mail.smtp.auth", "true")
(. props put "mail.transport.protocol", "smtps")
(def session (javax.mail.Session/getDefaultInstance props nil))
(def msg (javax.mail.internet.MimeMessage. session))
(. msg setFrom (javax.mail.internet.InternetAddress. "[email protected]"))
(. msg addRecipients javax.mail.Message$RecipientType/TO
"[email protected]")
(. msg setSubject "i am the subject")
(. msg setText "I am the body!!!")
(. msg setHeader "X-Mailer", "msgsend")
(. msg setSentDate (java.util.Date.))
; send the email
(def transport (. session getTransport))
(. transport connect "smtp.gmail.com" 465 "[email protected]" "password")
(. transport
sendMessage
msg
(. msg getRecipients javax.mail.Message$RecipientType/TO))
(. transport close)