#! /usr/bin/lua5.1 -- Some crappy IMAP functions in LUA 5.1 -- Copyright (C) 2009 Matous Jan Fialka, -- Released under the terms of The MIT License -- TODO: properly handle IMAP errors assert(require("socket")) local imap_accounts = {} function set_imap_accounts(a) assert(a) a.host, a.user, a.pass, a.sock = nil a.port = a.port or 143 imap_accounts = a end local function imap_login(n) assert(type(assert(n)) == "string") local a = assert(imap_accounts[n]) local h,u,p = assert(a.host), assert(a.user), assert(a.pass) local s = assert(socket.connect(h, a.port)) imap_accounts[n].sock = s if s:receive() then if s:send(". login "..u.." "..p.."\r\n") then if s:receive() then return true end end end return false end local function imap_logout(n) assert(type(assert(n)) == "string") local a = assert(imap_accounts[n]) assert(a.sock) if a.sock:send(". logout\r\n") then if a.sock:close() then a.sock = nil return true end end return false end local function imap_status(n,q) assert(type(assert(n)) == "string") local q,a,r = string.lower(assert(q)), assert(imap_accounts[n]) if a.sock:send(". status INBOX ("..q..")\r\n") then r = a.sock:receive() if not a.sock:receive() or not r then return -1 end r = string.match(r, string.upper(q).."%s+(%d+)") end return r or 0 end set_imap_accounts({ example1 = { host = "mail.example1.tld", user = "user@example1.tld", pass = "xxxxxxxx", }, example2 = { host = "mail.example2.tld", user = "user@example2.tld", pass = "xxxxxxxx", }, }) local u = nil local m = nil if imap_login("example2") then m = imap_status("example2", "messages") u = imap_status("example2", "unseen") imap_logout("example1") end print("Messages: "..m.." New: "..u)