我该如何使用Lua sockets / SMTP发送附件?

我有以下代码:

local email_credentials = function(email_address, password, username)
   local from
   local contents = read_email_contents_file()
   contents= string.gsub(contents, "<<password>>", password)
   from = "<CAdmin@test.net>"
   rcpt = {
   "<"..email_address..">"
   }
   mesgt = {
      headers = {
         to = email_address,
         ["content-type"] = 'text/html',
         subject = "Your Password"
     },
       body = contents
  }

  r, e = smtp.send{
     from = from,
     rcpt = rcpt,
     server = 'localhost',
     source = smtp.message(mesgt)
  }
end

找到了这个帖子:

http://lua-users.org/lists/lua-l/2005-08/msg00021.html

我尝试更改标题部分的内容:

  headers = {
     to = email_address,
     ["content-type"] = 'text/html',
     ["content-disposition"] = 'attachment; filename="/var/log/test.log"',
     subject = "test email with attachment"
 },

但那没有起作用。邮件已被发送/接收,但没有附件。

任何帮助将不胜感激。

谢谢

** EDIT 1 **

我添加了以下两行:

["content-description"] ='test description',
["content-transfer-encoding"] = "BASE64"

现在我得到了附件。但是,数据全部混乱。看起来像这样:

=«,ŠÝrm/'LŒq©ÚuÜ!jׯz»^ÆÜÁ©í¶‹aŠÇ¦j)

文件的内容只是普通文本... 谢谢

点赞
用户1078009
用户1078009

我找到了答案。需要包含 ltn12 库。

http://w3.impa.br/~diego/software/luasocket/old/luasocket-2.0-beta2/ltn12.html

我更新了我的代码,使其像以下代码一样:

local email_withattachment = function(email_address, path, filename)
   local from
   if (email_address == nil) or (path == nil) or (filename == nil) then
    return false
   end

   from = "<admin@test.net>"
   rcpt = {
   "<"..email_address..">"
   }
   mesgt = {
      headers = {
         to = email_address,
         ["content-type"] = 'text/html',
         ["content-disposition"] = 'attachment; filename="'..filename..'"',
         ["content-description"] ='yourattachment',
         ["content-transfer-encoding"] = "BASE64",
         subject = "subject line"
     },
      body = ltn12.source.chain(
        ltn12.source.file(io.open(path..filename, "rb")),
        ltn12.filter.chain(
          mime.encode("base64"),
          mime.wrap()
          )
        )
  }

  r, e = smtp.send{
     from = from,
     rcpt = rcpt,
     server = 'localhost',
     source = smtp.message(mesgt)
  }
  if e then
    return false
  end
  return true
end

我仍在努力阅读 LTN12 手册,以了解我究竟在做什么(哈哈),但代码能够工作。

希望这能帮助其他人。

2013-03-08 00:35:24