diff --git a/Lua-Examples.md b/Lua-Examples.md index 705497c..bae9889 100644 --- a/Lua-Examples.md +++ b/Lua-Examples.md @@ -35,6 +35,51 @@ function inbucket.after.message_deleted(msg) end ``` +## Event trigger: before message stored + +This event fires after Inbucket has accepted a message, but before it has been stored. + +Changes the destination mailbox to `test` for two specific recipients. + +```lua +local logger = require("logger") + +-- Original mailbox name on left, new on right. +local mailbox_mapping = { + ["swaks"] = "test", + ["james-test"] = "test", +} + +function inbucket.before.message_stored(msg) + local made_changes = false + local new_mailboxes = {} + + -- Loop over original recipient mailboxes for this message, building up list + -- of new_mailboxes. + for index, orig_box in ipairs(msg.mailboxes) do + local new_box = mailbox_mapping[orig_box] + if new_box then + logger.info(string.format("Mapping mailbox %q to %q", orig_box, new_box), {}) + new_mailboxes[index] = new_box + made_changes = true + else + -- No match, continue using the original value for this mailbox. + new_mailboxes[index] = orig_box + end + end + + if made_changes then + -- Recipient mailbox list was changed, return updated msg. + logger.info(string.format("New mailboxes: %s", table.concat(new_mailboxes, ", ")), {}) + msg.mailboxes = new_mailboxes + return msg + end + + -- No changes, return nil to signal inbucket to use original msg. + return nil +end +``` + ## Event trigger: after message stored Prints metadata of stored messages to STDOUT: