使用 Lua 发送邮件

如何使用 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
点赞
用户983070
用户983070

使用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
}

--记录SMTP结果和潜在错误
print(r,e)

还要确保在多部分邮件时正确使用LTN12模块 API链接SMTP消息:

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

或使用Mime模块 API进行换行:

body = mime.eol(0, [[
  应始终使用CRLF结尾的消息正文行。SMTP模块不会执行转换。但是,发送函数会执行SMTP填充,而消息函数则不会。
]])

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

2018-03-14 01:40:31