Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i send attachments using lua sockets / smtp?

I have the following code:

local email_credentials = function(email_address, password, username)
   local from 
   local contents = read_email_contents_file()
   contents= string.gsub(contents, "<<password>>", password)
   from = "<[email protected]>"
   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

Found this post:

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

I've tried changing the header section to look like:

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

but that didn't work. THe email sent / received but with no attachment.

Any help would be appreciated.

Thanks

EDIT 1

I've added the following two lines:

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

and now I get an attachment. However, the data is all jumbled. Looks like this:

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

The contents of the file is just text.... Thanks

like image 278
dot Avatar asked May 14 '26 09:05

dot


1 Answers

I found the answer. needed to include the library ltn12.

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

I updated my code so that it looks like the following:

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 = "<[email protected]>"
   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

I'm still trying to read thorugh the LTN12 manual to understand what exactly I'm doing (lol) but the code works.

Hope this helps someone else.

like image 153
dot Avatar answered May 16 '26 07:05

dot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!