Lumail - The console email client


Examples: html2text()

The following code uses the on_get_body() function to convert HTML mails to plain-text, using lynx.

Although this conversion is basic it seems to work pretty well.

function on_get_body()

   --
   -- If we don't have lynx we can't do anything ..
   ---
   if ( not executable( "/usr/bin/lynx" ) ) then
      return( "" )
   end

   parts = get_body_parts()

   --
   -- Do we have text/plain?  If so return it immediately.
   --
   -- Otherwise store the text/html part.
   --
   html = nil

   for index,type in ipairs( parts ) do
      if ( type == "text/plain" ) then
         --
         -- There are two things we could do here
         --
         --  1.  return( "" ) - Allow normal processing.
         --
         --  2.  return(get_body_part(index)) - Explicitly return
         --     the first text/plain part we've found.
         --
         return(get_body_part( index ))
      end
      if ( type == "text/html" ) then

         -- Save the HTML part away.
         html = get_body_part( index )
      end
   end

   --
   -- If we have a HTML part, then convert it to plain-text via lynx
   --
   if ( html ) then

      -- 1.  write to a temporary file
      file = os.tmpname ()
      ff = io.open( file , "w" );
      ff:write( html );
      ff:close();

      -- 2.  run the command
      local fh  = assert(io.popen("/bin/cat " .. file .. " | /usr/bin/lynx -dump -stdin", "r"))
      local out = assert(fh:read('*a'))
      fh:close()

      -- 3.  cleanup
      os.remove( file )

      -- 4.  Add a wee header.
      out = "This mail was converted from HTML via Lynx\n\n" .. out
      return( out );
   end

   --
   -- Normal processing.
   return ""
end