Programmatically adding an Excel attachment

G

gregarican

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?
 
G

gregarican

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 <[email protected]>
To: You <[email protected]>
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, '(e-mail address removed)', '(e-mail address removed)')
end
rescue Exception => e
print "Exception occured: " + e
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top