Hello,
I've changed a little original script for sending an email. Below script can send an email to a few recipients with a few files in the attachement not only one file. You can use it for example for sending images from a few cameras or sending camera image and .csv file.
This script is an updated version of above script from Edgars:
Example of use:
I've changed a little original script for sending an email. Below script can send an email to a few recipients with a few files in the attachement not only one file. You can use it for example for sending images from a few cameras or sending camera image and .csv file.
This script is an updated version of above script from Edgars:
Code:
-- send an e-mail with attachments
function mailattach(to, subject, message, files)
-- make sure these settings are correct
local settings = {
-- "from" field, only e-mail must be specified here
from = 'user@gmail.com',
-- smtp username
user = 'user@gmail.com',
-- smtp password
password = 'user',
-- smtp server
server = 'smtp.gmail.com',
-- smtp server port
port = 465,
-- enable ssl, required for gmail smtp
secure = 'sslv23',
}
local smtp = require('socket.smtp')
if type(to) ~= 'table' then
to = { to }
end
for index, email in ipairs(to) do
to[ index ] = '<' .. tostring(email) .. '>'
end
-- escape double quotes in file name
for _, object in ipairs(table) do
files[_].filename = files[_].filename:gsub('"', '\\"')
end
-- message headers and body
email = {headers = {}, body = {}}
email.headers = { to = table.concat(to, ', '), subject = subject, }
email.body[1] = { headers = { ['Content-Type'] = 'text/html; charset=utf-8', }, body = mime.eol(0, message) }
-- adding attachements
for _, object in ipairs(files) do
email.body[_+1] = {
headers = { ['Content-Type'] = files[_].mimetype or 'text/plain', ['Content-Disposition'] = 'attachment; filename="' .. files[_].filename ..'"', ['Content-Transfer-Encoding'] = 'BASE64', },
body = ltn12.source.chain( ltn12.source.string(files[_].filedata), ltn12.filter.chain(mime.encode('base64'), mime.wrap() ) )
}
end
settings.source = smtp.message(email)
-- fixup from field
settings.from = '<' .. tostring(settings.from) .. '>'
settings.rcpt = to
return smtp.send(settings)
end
Example of use:
Code:
-- email parameters
to = {
'first@gmail.com',
'second@gmail.com'
}
subject = 'Email with a few attachements'
message = 'Email with a few attachements. Please check them.'
files = {
{filename = 'Image1.jpg', filedata = io.readfile('/www/scada/resources/img/Image1.jpg'), mimetype = 'jpg'},
{filename = 'Image2.jpg', filedata = io.readfile('/www/scada/resources/img/Image2.jpg'), mimetype = 'jpg'}
}
-- send an e-mail with attachments
mailattach(to, subject, message, files)