Lua Event: After Message Stored
This event fires after Inbucket has accepted and stored a message.
Examples
Print Metadata
This example prints the metadata of stored messages to the console. Using
print()
instead of logging is not advised, but this demonstrates the fields
available on the message paramter.
function inbucket.after.message_stored(msg)
print("\n## message stored ##")
print(string.format("mailbox: %s", msg.mailbox))
print(string.format("id: %s", msg.id))
print(string.format("from: %q <%s>", msg.from.name, msg.from.address))
-- Loop over each To address.
for i, to in ipairs(msg.to) do
print(string.format("to[%s]: %q <%s>", i, to.name, to.address))
end
-- Format the unix timestamp in a human readable way.
print(string.format("date: %s", os.date("%c", msg.date)))
print(string.format("size: %s", msg.size))
print(string.format("subject: %s", msg.subject))
end
Example output:
## message stored ##
mailbox: test
id: 8
from: "" <james@localhost>
to[1]: "" <test@inbucket.local>
date: 22 Mar 24 15:09 PDT
subject: Test from Outlook
Webhook style HTTP post as JSON
In this example, message metadata is converted to JSON and a POST request is made to an external web service:
local http = require("http")
local json = require("json")
BASE_URL = "https://myapi.example.com"
function inbucket.after.message_stored(msg)
local data = {
sender = string.format("Mail from %q", msg.from.address),
subject = msg.subject
}
-- Encode the data table above as JSON.
local body = json.encode(data)
-- POST JSON or fail.
assert(http.post(BASE_URL .. "/notify/text", {
headers = { ["Content-Type"] = "application/json" },
body = body,
}))
end
Example JSON body:
{"subject":"Test from Outlook","sender":"Mail from \"james@localhost\""}
Write to file
An example that may be relevant for continuous integration testing. It writes metadata to temporary file and runs external shell command on it:
function inbucket.after.message_stored(msg)
local content = string.format("%q,%q\n", msg.from.address, msg.subject)
-- Write content to temporary file.
local fnam = os.tmpname()
local f = assert(io.open(fnam, "w+"))
assert(f:write(content))
f:close()
local cmd = string.format("cat %q", fnam)
print(string.format("\n### running %s ###", cmd))
local status = os.execute(cmd)
if status ~= 0 then
error("command failed: " .. cmd)
end
end
Example output:
### running cat "/tmp/63708877" ###
"james@localhost","Test from Outlook"