Derrick Bradley
Derrick Bradley

Reputation: 39

How do I loop through an array when sending an email with the mail gem in Ruby?

I'm trying to loop through an array in the body of an email using the gmail gem (which, as I understand it, uses the mail gem for sending mail).

How do I loop through an array in the body of an email using the mail gem? Seems so simple, and yet, I can't get it going.

The method below doesn't work, but shows what I'd like to do.

def deliver_mail(gmail, email, result, request_type)
  client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => 'bigmake_development')
  investments = client.query("SELECT * FROM investments WHERE investor_id = '#{result[:id]}'")

  gmail.deliver do
    to email.from_addrs
    subject "My Subject!"

    body do
      investments.each do |i|
        i['target']
        i['deal_type']
        i['round']
        i['deal_date']
      end
    end  
  end
  puts "Email reply sent to #{email.from_addrs}"
end

Working examples that I've seen are usually formatted like this:

def deliver_mail(gmail, email, result, request_type)
  gmail.deliver do
    to email.from_addrs
    subject "My Subject!"
    body "Hello!"
    # or like this
    body File.load('body.txt')
  end
end

However, I don't think either of those methods will work very well.

Upvotes: 0

Views: 386

Answers (1)

girasquid
girasquid

Reputation: 15526

Aren't you just trying to build a string? Something like this should work:

  body_content = ""
  investments.each do |i|
    body_content += "#{i['target']} #{i['deal_type']} #{i['round']} #{i['deal_date']}\n"
  end
  gmail.deliver do
    to email.from_addrs
    subject "My Subject!"
    body body_content
  end

If you wanted to get more complex, I would look into something like ERB.

Upvotes: 2

Related Questions