2013-03-07 278 views
2

我有以下代碼:我如何使用lua socket/smtp發送附件?

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 

發現這個職位:

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" 
}, 

但沒沒有工作。發送/接收的電子郵件,但沒有附件。

任何幫助,將不勝感激。

由於1

我已經添加了以下兩行

編輯:

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

,現在我得到一個附件。但是,數據全是混亂的。看起來是這樣的:

=«!,ŠÝrm/「10當量©UUUĴ×Z»^ÆÜÁ©í¶

該文件的內容是文本。 ... 謝謝

+0

您是否真的在base64中編碼過「內容」? – Ignacio 2013-03-08 00:32:13

回答

0

我找到了答案。需要包括圖書館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 = "<[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 

我仍然試圖讀取thorugh的LTN12說明書,瞭解我在做什麼(笑)但代碼有效。

希望這可以幫助別人。