Luasec - send email via gmail using SMTP

737 Views Asked by At

I have tried using luasec to connect to my gmail account and send email via SMTP, and though after a while I was able to allow insecure apps to connect, I'd like to find out how to implement a secure connection via gmail.

I've used the following code, that I found here, where the socket connection is wrapped by ssl before connecting to gmail, but google still says the connection is insecure.

local socket = require 'socket'
local smtp = require 'socket.smtp'
local ssl = require 'ssl'
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

I even went as far as creating a self signed certificate and using it as a variable in the ssl wrap, but still gmail identifies the connection as being insecure. Do we need to change the protocol or does the luasec library need updating?

On that note, neither have I been unable to send email via hotmail / outlook.com

1

There are 1 best solutions below

4
Josh On

Regarding Gmail:

Take a look here. Essentially, Google took it upon themselves to say, "Hey, we want to make every account safe, so we refuse to let less secure applications access our users' Gmail accounts!" Thankfully, you can turn it off, or I would have never been able to use Fossamail as my e-mail client.

It may be the same situation for Hotmail/Outlook, though I don't use them myself.