How to send all files in a folder as email attachments using ruby

currenty i am able to send one file as email attachment using the following code ,

require ‘net/smtp’

filename = “/tmp/test.txt”

Read a file and encode it into base64 format

filecontent = File.read(filename)
encodedcontent = [filecontent].pack(“m”) # base64

marker = “AUNIQUEMARKER”

body =<<EOF
This is a test email to send an attachement.
EOF

Define the main headers.

part1 =<<EOF
From: Private Person me@fromdomain.net
To: A Test User test@todmain.com
Subject: Sending Attachement
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: multipart/mixed; name="#{filename}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"

#{encodedcontent}
–#{marker}–
EOF

mailtext = part1 + part2 + part3

Let’s put our code in safe area

begin
Net::SMTP.start(‘localhost’) do |smtp|
smtp.sendmail(mailtext, ‘me@fromdomain.net’,
[‘test@todmain.com’])
end
rescue Exception => e
print "Exception occured: " + e
end

Have you considered using the Mail gem for building your email? GitHub - mikel/mail: A Really Ruby Mail Library

Working with what you have, you could put the file loading stuff together and then just loop over the directory contents.

# Drop the first two entries (".", ".."), and select only files.
Dir.entries('some_directory').drop(2).select { |f| File.file?(f) }.each do |filename|
   mailtext << # Do your file stuff here
end

Unless this is some sort of homework assignment, I’d strongly suggest using the mail gem.

1 Like