Email with attachment

Sending email with attachment #

Place mailattach function in Scripting > Common functions.

Change settings table as needed.

-- send an email with attachment
function mailattach(to, subject, message, filename, filedata, mimetype)
  -- make sure these settings are correct
  local settings = {
    -- "from" field, only email must be specified here
    from = 'example@gmail.com',
    -- smtp username
    user = 'example@gmail.com',
    -- smtp password
    password = 'mypassword',
    -- smtp server
    server = 'smtp.gmail.com',
    -- smtp server port
    port = 465,
    -- enable ssl, required for gmail smtp
    secure = 'tlsv12',
  }

  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
  filename = filename:gsub('"', '\\"')

  -- message headers and body
  settings.source = smtp.message({
    headers = {
      to = table.concat(to, ', '),
      subject = subject,
      From = '<' .. tostring(settings.from) .. '>',
    },
    body = {
      {
        headers = {
          ['Content-Type'] = 'text/html; charset=utf-8',
        },
        body = mime.eol(0, message)
      },
      {
        headers = {
          ['Content-Type'] = mimetype or 'text/plain',
          ['Content-Disposition'] = 'attachment; filename="' .. filename .. '"',
          ['Content-Transfer-Encoding'] = 'BASE64',
        },
        body = ltn12.source.chain(
          ltn12.source.string(filedata),
          ltn12.filter.chain(mime.encode('base64'), mime.wrap())
        )
      }
    }
  })

  -- fixup from field
  settings.from = '<' .. tostring(settings.from) .. '>'
  settings.rcpt = to

  return smtp.send(settings)
end

You need to enable less secure apps inside your gmail account
https://www.google.com/settings/security/lesssecureapps

Function parameters:

  • to - recipient's email address
  • subject - email subject
  • message - email message
  • filename - name of the attachment file that will appear in the email
  • filedata - attachment file data (binary string)
  • mimetype - mime type of attachment, defaults to text/plain when not specified

Example:

-- send file as report.csv with text/csv mime type

to = 'someone@example.com'
subject = 'CSV report'
message = 'CSV file attached'
filename = 'report.csv'
filedata = io.readfile('/home/ftp/report.csv')
mimetype = 'text/csv'

res, err = mailattach(to, subject, message, filename, filedata, mimetype)
log(res, err)