Tuesday, July 26, 2011

Dynamically Attaching MULTIPLE Files to Emails in Ruby Using Pony

I struggled with this one a bit, so I figured I'd share it with those that may be in a similar place.  Okay, so here was the goal - obtain the directory listings of a folder (which contained folders named after recipients) and recursively find every file in the recipient folder.  Once a file(s) is found in the corresponding recipient folder, add the file(s) as an attachment to one email.  Pheww, that can take the breath out of a person.  If you have a better way of accomplishing this goal, then please share! :) 

#!/usr/bin/env ruby
require 'pony'
smtp_relay = "smtp_relay.somedomain.com"
name_root = “~/my_mail_list_dir/”
attachment_hash = {}
Dir.entries(name_root).each do |name|
  # Replace message text with name
  msg_body = File.read("~/email_msg.txt").gsub("NAME_OF_PERSON", name)

  # Recurse each name folder and find corresponding files to add as attachments 

  Dir["#{name_root}/#{name}/**"].each do |attachment|
    if File.file?(current_attachment) == true
      current_attachment_name = File.basename(current_attachment)
      attachment_hash["#{current_attachment_name}"] = "#{File.binread(current_attachment)}"
    end
  end

  Pony.mail(
    :to => "destination@domain.com",
    :from => "source@otherdestination.com",
    :subject => "The Subject",
    :body => msg_body,
    :attachments => attachment_hash,
    :via => :smtp,
    # It's important to note that you should use SMTPS (TCP port 465) 

    # whenever possible - I only had a inadequate SMTP (TCP port 25)
    # relay at my disposal at the time of this writing
    :via_options => {
      :address => smtp_relay,
      :port => 25,
      :enable_starttls_auto => false
    }
  )

  # Reset attachments for new owner
  attachment_hash = {}
end


Hope it helps ya! Cheers!

No comments:

Post a Comment