用Lua发送电子邮件

时间:2018-03-13 12:39:21

标签: email lua smtp

您如何使用Lua发送电子邮件? 我和之合作的团队有一个邮件服务器,那有什么关系吗? 以下是我使用的代码:

function send_email (email_to, email_subject, email_message)
  local SMTP_SERVER = "mail.server.com"
  local SMTP_AUTH_USER = "mail@domain.com"
  local SMTP_AUTH_PW = "password"
  local SMTP_PORT = "587"
  local USER_SENDING = "mail@domain.com"

  local smtp = require("socket.smtp")
  local rcpt = {email_to}
  local mesgt = {
    headers = {
      to = email_to,
      from = USER_SENDING,
      subject = email_subject
    },
      body = email_message
  }
  local r, e = smtp.send{
    from  = USER_SENDING,
    rcpt  = rcpt,
    source  = smtp.message(mesgt),
    server = SMTP_SERVER,
    port = SMTP_PORT,
    user = SMTP_AUTH_USER,
    password = SMTP_AUTH_PW
  }
end

1 个答案:

答案 0 :(得分:1)

使用LuaSocket SMTP API。

您的示例看起来正确,请仔细检查SMTP设置并记录结果:

local r, e = smtp.send{
  from  = USER_SENDING,
  rcpt  = rcpt,
  source  = smtp.message(mesgt),
  server = SMTP_SERVER,
  port = SMTP_PORT,
  user = SMTP_AUTH_USER,
  password = SMTP_AUTH_PW
}

-- Log SMTP results and potential errors
print(r, e)

另外,请确保在多部分时使用LTN12 module API正确链接SMTP邮件:

  body = ltn12.source.chain(
    ltn12.source.file(io.open("image.png", "rb")),
    ltn12.filter.chain(
      mime.encode("base64"),
      mime.wrap()
    )
  )

或EOL的Mime module API:

  body = mime.eol(0, [[
    Lines in a message body should always end with CRLF. 
    The smtp module will *NOT* perform translation. However, the 
    send function *DOES* perform SMTP stuffing, whereas the message
    function does *NOT*.
  ]])

LuaSocket SMTP API文档中有一个更详细的例子。