Programmatically adding an Excel attachment


#1

I’ve checked out this page -->
http://www.tutorialspoint.com/ruby/ruby_sending_email.htm
that shows how to e-mail a text file attachment.I’m trying to attach
an Excel file, but the receiver gets a corrupted file attachment. I’ve
changed the Content-Type: in the MIME header to application/vnd.ms-
excel but it doesn’t seem to work. Anyone care to offer a quick code
snippet that will fit the bill?


#2

On Jan 15, 4:23 pm, gregarican removed_email_address@domain.invalid wrote:

I’ve checked out this page -->http://www.tutorialspoint.com/ruby/ruby_sending_email.htm
that shows how to e-mail a text file attachment.I’m trying to attach
an Excel file, but the receiver gets a corrupted file attachment. I’ve
changed the Content-Type: in the MIME header to application/vnd.ms-
excel but it doesn’t seem to work. Anyone care to offer a quick code
snippet that will fit the bill?

I solved my own problem. It was just a question of me not parsing the
Excel file correctly. Since I was basing things off sample code that
opened plain text files to send as attachments, I wasn’t building the
attachment properly. Here’s a snipped of my little routine. Works like
a champ, and I didn’t have to install ActionMailer or any other module
since I cobbled the code together manually. It will fit the bill!

Code is below if anyone runs into a similar quandary.


Read a file and encode it into base64 format

savedDoc = path+filename
file = File.open(savedDoc, ‘rb’)
filecontent = file.read()
encodedcontent = [filecontent].pack(“m*”) # base64

marker = “AUNIQUEMARKER”

body =<<EOF
Attached is your Excel spreadsheet!
EOF

Define the main headers.

part1 =<<EOF
From: Me removed_email_address@domain.invalid
To: You removed_email_address@domain.invalid
Subject: Message with Excel Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
–#{marker}
EOF

Define the message action

part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding: 8bit

#{body}
–#{marker}
EOF

Define the attachment section

part3 =<<EOF
Content-Type: application/vnd.ms-excel; name="#{filename}"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="#{filename}"
Content-Description: “#{filename}”

#{encodedcontent}
–#{marker}–
EOF

mailtext = part1 + part2 + part3

Let’s put our code in safe area

begin
Net::SMTP.start(server=localhost, port=25) do |smtp|
smtp.sendmail(mailtext, ‘removed_email_address@domain.invalid’, ‘removed_email_address@domain.invalid’)
end
rescue Exception => e
print "Exception occured: " + e
end