Rokiのチラ裏

学生による学習のログ

lua de gmail

単なるメール送信のためにメールクライアントを起動したりブラウザを起動したり、sendmail コマンドを設定するのは面倒だったので lua でそのような用途の簡易的なスクリプトを書いたのだが、lua を書く事自体本当に久しぶりだった。Gist に上げるまでもないが、どこかに置いておきたかったので、取り敢えずブログに貼り付ける事とした。

-- readConf.lua
local json = require "cjson"
local lfs = require "lfs"
local doc_path = "./"

function readConf()
    val = {}
    local result, file
    
    for filename in lfs.dir(doc_path) do
        result = string.find(filename, "mailconf.json")
        if result ~= nil then
            file = io.open(filename, "r")
            io.input(file)
            val = json.decode(io.read())
            io.close(file)
        end
    end
    return val
end
-- sendMail.lua
local socket = require "socket"
local smtp = require "socket.smtp"
local mime = require "mime"
local ssl = require "ssl"
local https = require "ssl.https"
local ltn12 = require "ltn12"

local function headerEncode(src)
    return "=?UTF-8?B?" .. mime.b64(src) .. "?="
end

local function sslCreate()
    local sock = socket.tcp()
    return setmetatable({
        connect = function(_, host, port)
            local r, e = sock:connect(host, port)
            if not r then return r, e end
            sock = ssl.wrap(sock, {mode = "client", protocol = "tlsv1"})
            return sock:dohandshake()
        end
    }, {
        __index = function(t, n)
            return function(_, ...)
                return sock[n](sock, ...)
            end
        end
    })
end

function sendMessage(j, to_receiver, subject, body)
    local msg = {
        headers = {
            from = headerEncode(j.Name) .. " <" .. j.UserName .. ">",
            to = headerEncode(to_receiver["Name"]) .. " " .. to_receiver["Address"], 
            subject = headerEncode(to_receiver["Subject"]),
            ["content-type"] = 'text/plain; charset="utf-8"'
        },
        body = to_receiver["Body"]
    }
    local ok, err = smtp.send {
        from = "<".. j.UserName .. ">",
        rcpt = "<" .. to_receiver["Address"] .. ">",
        source = smtp.message(msg),
        user = j.UserName,
        password = j.Password,
        server = "smtp.gmail.com",
        port = 465,
        create = sslCreate
    }
    if not ok then
        print("Mail send failed ", err)
    end
end
-- main.lua
dofile("sendMail.lua");
dofile("readConf.lua");

sendMessage(readConf(), {Name = "xxx 様", Address = "example@mail.com", Subject = "件名", Body = "こんにちは"})

以下のような json ファイルから設定を読み込む。

{ "UserName": "example@example.com", "Password": "password", "Name": "watashi" }

なんだか懐かしい。