Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua send mail with gmail account

Tags:

email

lua

I want to send email with my gmail account, I gave it a try, but no luck, so is anyone can give me a sample? Any suggestions would be appreciated. Thank you

I used lualogging api, the code is

require"logging.email"

logger = logging.email {
  rcpt = "[email protected]",
  from = "[email protected]",
  user = "[email protected]",
  password = *****,
  server = "smtp.gmail.com",
  port = 587,
  headers = { 
    rcpt = "[email protected]",
    from = "[email protected]", 
    subject = "[%level] logging.email test", 
  },
}

logger:error("error!")
like image 720
ms2008 Avatar asked Jun 17 '12 10:06

ms2008


1 Answers

You should look at LuaSocket, especially its SMTP module which can be used to send mail using your GMail account. You also need a SSL library, I use LuaSec which was designed to be used together with LuaSocket. This is the code I successfully used to send emails using my GMail account:

-- Michal Kottman, 2011, public domain
local socket = require 'socket'
local smtp = require 'socket.smtp'
local ssl = require 'ssl'
local https = require 'ssl.https'
local ltn12 = require 'ltn12'

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(subject, body)
    local msg = {
        headers = {
            to = 'Your Target <target email>',
            subject = subject
        },
        body = body
    }

    local ok, err = smtp.send {
        from = '<your email>',
        rcpt = '<target email>',
        source = smtp.message(msg),
        user = 'username',
        password = 'password',
        server = 'smtp.gmail.com',
        port = 465,
        create = sslCreate
    }
    if not ok then
        print("Mail send failed", err) -- better error handling required
    end
end
like image 191
Michal Kottman Avatar answered Sep 22 '22 01:09

Michal Kottman