Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send emails to multiple recipients with Ruby Mail.rb

Tags:

email

ruby

I've written a small script to send out emails with attachments in Ruby. It works like a charm as long as there is a single recipient, however I need to send out mails to a list of recipients. The recipients are stored in a yaml file, which is being read by the script and then emails are sent to each recipient with the help of a loop:

Mail.defaults do
delivery_method :smtp, options
end

mail['mail_to'].each do |i|
    mail = Mail.new do 
        to i
        from mail['mail_from']
        subject mail_subject
        body mail_body
        add_file    :filename => 'Report.pdf', :content => File.read(global['filename_pdf'])
end
    mail.deliver!
end

However this only works for the first recipient, afterwards ruby throws this:

/home/juwi/.gem/ruby/1.9.1/gems/mail-2.5.4/lib/mail/check_delivery_params.rb:5:in `check_delivery_params': An SMTP From address is required to send a message. Set the message smtp_envelope_from, return_path, sender, or from address. (ArgumentError)
from /home/juwi/.gem/ruby/1.9.1/gems/mail-2.5.4/lib/mail/network/delivery_methods/smtp.rb:98:in `deliver!'
from /home/juwi/.gem/ruby/1.9.1/gems/mail-2.5.4/lib/mail/message.rb:248:in `deliver!'
from main.rb:47:in `block in <main>'
from main.rb:33:in `each'
from main.rb:33:in `<main>'

I don't really understand why that happens. So I'd love to be enlightened, here!

like image 872
juwi Avatar asked May 28 '13 08:05

juwi


2 Answers

Another approach that might work in many contexts is to use a comma separated list in the to field - eg.

  mail = Mail.new do
    from    'me@my_domain.com'
    to      'me@my_domain.com, [email protected]'
    subject 'test'
    body    'message'
  end

From: https://github.com/mikel/mail/blob/master/lib/mail/elements/address_list.rb

Mail::AddressList requires a correctly formatted group or mailbox list per RFC2822 or RFC822. It also handles all obsolete versions in those RFCs.

like image 157
Ross Attrill Avatar answered Oct 29 '22 17:10

Ross Attrill


I just found the answer after realizing that I get nil from the second run of the loop onwards. It seems, that Ruby tries to iterate over the "from" field as if it were an array. So I explicitly added a variable for it, and that solved it.

like image 27
juwi Avatar answered Oct 29 '22 15:10

juwi