kattashri
kattashri

Reputation: 267

HTML format of smtp in ruby to send mail

I wrote a ruby script to send mails using smtp by reading the contents of a file. The contents of a file are:

+3456|0|2013-04-16|2013-04-19
+3456|0|2013-04-16|2013-05-19

And my code to send the mail is as below:

content = File.read(file_name)   
message = << MESSAGE_END   
From: [email protected]
To: [email protected]
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP e-mail test
Body
**HTML CODE to display the table with rows equal to the number of records in the file**
MESSAGE_END

Net::SMTP.start('localhost') do |smtp| 
  smtp.send_message message, '[email protected]','[email protected]'
end

Now my problem is how to write an html code to create a table with rows and columns equal to the number of records inside the file(as the records in the file varies accordingly)? The records in the file are always '|' separated.

Upvotes: 1

Views: 547

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

Suppose your input file is located at ./input.txt, then you could do something like this:

require 'builder'

html = Builder::XmlMarkup.new
html.table do
  File.open('./input.txt', 'r').each_line do |line|
   html.tr do
      line.chomp.split('|').each do |column|
        html.td column
      end
    end
  end
end

message << html.to_html

Upvotes: 0

AJcodez
AJcodez

Reputation: 34166

You can use content_tag helper and String#split. For example:

def row_markup(row)
  content_tag(:tr) do
    row.map{ |elem| content_tag(:td, elem) }.reduce(:+)
  end
end

def table_markup(rows)
  content_tag(:table) do
    rows.map{ |row| row_markup(row.split("|")) }.reduce(:+)
  end
end

then call

table_markup(read_data_from_file.split("\n"))

Upvotes: 1

Related Questions