send_email_worker.lua

changeset 0
a4670b074c77
--- /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;

mercurial