邮件箱解析 |
|
假设您将源代码保存在当前目录(或您 PackagePath 中的其它位置)中,名为 mboxparser.lua
。在您的代码中,添加
parse = require "mboxparser"
主函数 parse.mbox
接收邮件箱文件内容作为字符串,并返回一个包含每个邮件的条目表。每个条目具有以下结构
message = { headers = { [["name_1"]] = "value_1", [["name_2"]] = "value_2", ... ... [["name_n"]] = "value_n", }, body = "message body" }
因此,如果一个邮件箱具有以下内容
From [email protected] Thu Nov 22 13:59:05 2001 Date: Thu, 22 Nov 2001 13:59:04 -0200 (EDT) From: Whoever Smith <[email protected]> To: Other Smith <[email protected]> Subject: This is a test message Content-Type: TEXT/PLAIN; charset=US-ASCII Hi, This is the message body. Regards, Diego.
在它上面调用 parse.mbox
将返回以下表
messages = { { headers = { from = "Whoever Smith <[email protected]>", subject = "This is a test message", to = "Other Smith <[email protected]>", date = "Thu, 22 Nov 2001 13:59:04 -0200 (EDT)", ["content-type"] = "TEXT/PLAIN; charset=US-ASCII", }, body = "Hi, This is the message body. Regards, Diego.", } }
local Public = {} local strfind, strlower, gsub = string.find, string.lower, string.gsub local strsub, tinsert = string.sub, table.insert function Public.headers(headers_s) local headers = {} headers_s = "\n" .. headers_s .. "$$$:\n" local i, j = 1, 1 local name, value, _ while 1 do j = strfind(headers_s, "\n%S-:", i+1) if not j then break end _, _, name, value = strfind(strsub(headers_s, i+1, j-1), "(%S-):(.*)") value = gsub(value or "", "\r\n", "\n") value = gsub(value, "\n%s*", " ") name = strlower(name) if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end i, j = j, i end headers["$$$"] = nil return headers end function Public.message(message_s) message_s = gsub(message_s, "^.-\n", "") local _, headers_s, body _, _, headers_s, body = strfind(message_s, "^(.-\n)\n(.*)") headers_s = headers_s or "" body = body or "" return { headers = Public.headers(headers_s), body = body } end function Public.mbox(mbox_s) local mbox = {} mbox_s = "\n" .. mbox_s .. "\nFrom " local i, j = 1, 1 while 1 do j = strfind(mbox_s, "\nFrom ", i + 1) if not j then break end tinsert(mbox, Public.message(strsub(mbox_s, i + 1, j - 1))) i, j = j, i end return mbox end return Public
最初的 Lua 4 代码由 DiegoNehab 创建,用于测试 LuaSocket
[1] 1.4 SMTP 代码。Lua 5 版本由 DirkLaurie 制作。