# HG changeset patch # User Matthew Wild # Date 1327013249 0 # Node ID a4670b074c77f3d99c6f77441b3be95fb3d4f3ea Initial commit diff -r 000000000000 -r a4670b074c77 sample_config.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sample_config.lua Thu Jan 19 22:47:29 2012 +0000 @@ -0,0 +1,19 @@ +config = { + from_name = "Mr Email Sender"; + from_address = "hi@example.com"; + subject = "An example email"; + template = [[ + Hi $name! + + $content + + Goodbye, + Mr E. Sender + ]]; + + smtp_username = "user"; + smtp_password = "pass"; + smtp_server = "smtp.sendgrid.net"; + smtp_port = 587; +} + diff -r 000000000000 -r a4670b074c77 send_email_worker.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/send_email_worker.lua Thu Jan 19 22:47:29 2012 +0000 @@ -0,0 +1,42 @@ +dofile(assert(arg[1], "No config file specified")); +local config = assert(config, "No config!"); + +local beanstalk = require "beanstalk".new(); +local smtp = require "socket.smtp"; +local json = require "json"; + +local email_format = "%s <%s>"; + +beanstalk:connect(); + +-- A function that strips indentation and +-- replaces $variables with entries from the data table. +local function preprocess_message(data, message) + local indentation = message:match("^%s*"); + return (("\n"..message):gsub("\n"..indentation, "\n"):gsub("%$([%a_]+)", data):gsub("%s+$", "")); +end + + +repeat local job, err = beanstalk:reserve(); + if not job then + print("EE", err); + else + local data = json.decode(job.data); + assert(smtp.send { + from = email_format:format(config.from_name, config.from_address); + rcpt = data.address; + source = smtp.message { + headers = { + to = email_format:format(data.name or "", data.address); + from = email_format:format(config.from_name, config.from_address); + subject = config.subject; + }; + body = preprocess_message(data, config.message); + }; + user = config.smtp_username; + password = config.smtp_password; + server = config.smtp_server; + port = config.smtp_port; + }); + end +until false;