lua send mail with gmail account

前端 未结 2 1349
一向
一向 2020-12-30 13:37

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

相关标签:
2条回答
  • 2020-12-30 13:46

    The code from Michal Kottman works properly but it fails (for me) when smpt server works on 587 port, using a pretty different way to accept mail to send (according wo what I read). Does anybody faced anything similar? I always obtain "wrong version number" on server working on port 587.

    0 讨论(0)
  • 2020-12-30 13:50

    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
    
    0 讨论(0)
提交回复
热议问题