当前位置 : 主页 > 网络编程 > lua >

电子邮件 – lua用gmail帐户发送邮件

来源:互联网 收集:自由互联 发布时间:2021-06-23
我想用我的Gmail帐户发送电子邮件,我试一试,但没有运气,所以有人可以给我一个样品吗?任何建议,将不胜感激.谢谢 我使用了lualogging api,代码是 require"logging.email"logger = logging.email { rcpt
我想用我的Gmail帐户发送电子邮件,我试一试,但没有运气,所以有人可以给我一个样品吗?任何建议,将不胜感激.谢谢

我使用了lualogging api,代码是

require"logging.email"

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

logger:error("error!")
您应该查看 LuaSocket,尤其是 SMTP module,它可以用于使用您的GMail帐户发送邮件.您还需要一个SSL库,我使用的是 LuaSec,它与LuaSocket一起使用.这是我使用我的GMail帐户成功发送电子邮件的代码:

-- 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
网友评论