send_email_worker.lua

1
dofile(assert(arg[1], "No config file specified"));
2
local config = assert(config, "No config!");
3
 
4
local beanstalk = require "beanstalk".new();
5
local smtp = require "socket.smtp";
6
local json = require "json";
7
 
8
local email_format = "%s <%s>";
9
 
10
beanstalk:connect();
11
 
12
-- A function that strips indentation and
13
-- replaces $variables with entries from the data table.
14
local function preprocess_message(data, message)
15
	local indentation = message:match("^%s*");
16
	return (("\n"..message):gsub("\n"..indentation, "\n"):gsub("%$([%a_]+)", data):gsub("%s+$", ""));
17
end
18
 
19
 
20
repeat local job, err = beanstalk:reserve();
21
	if not job then
22
		print("EE", err);
23
	else
24
		local data = json.decode(job.data);
25
		assert(smtp.send {
26
			from = email_format:format(config.from_name, config.from_address);
27
			rcpt = data.address;
28
			source = smtp.message {
29
				headers = {
30
					to = email_format:format(data.name or "", data.address);
31
					from = email_format:format(config.from_name, config.from_address);
32
					subject = config.subject;
33
				};
34
				body = preprocess_message(data, config.message);
35
			};
36
			user = config.smtp_username;
37
			password = config.smtp_password;
38
			server = config.smtp_server;
39
			port = config.smtp_port;
40
		});
41
	end
42
until false;