Tonight I wanted to accomplish something easy. Read a list of email addresses from a CSV file and send a generic message to those email addresses.

Here is the code I came up with in about 5 minutes or so.

require'net/smtp'addresses=File.read('addresses.csv').split(',').map(&:strip)from="example@example.com"smtp=Net::SMTP.new('smtp.gmail.com',587)smtp.enable_starttlssmtp.start(Socket.gethostname,"#{from}",'a_password',:login)do|smtp|addresses.eachdo|to|message=<<EOM
From: Someone <#{from}>
To: Someone2 <#{to}>
Subject: This is from Ruby
Date: #{Time.now.strftime("%d/%m/%Y %H:%M")}
This email was sent using Ruby
EOM
beginsmtp.send_message(message,"#{from}","#{to}")rescueException=>eputseendendend

Look at this:

addresses=File.read('addresses.csv').split(',').map(&:strip)

There you go CSV read, and I have an array of the email addresses.

The rest of the code I have already spoken about in this [post][email]. One thing that I am curious about is the message variable. There must be a more efficient way to do that? Though the performance hit right now is tiny I don’t want to get into the habit of writing inefficient / slow code. I only spent around 5 minutes on this and clearly it can be done and should be done better. Therefore, my mission for the rest this week is to find a way to make that bit of code more concise and make the whole loop more efficient.

Right now is also a good time to dive into the many different gems that give you the ability to send an email. I am going to discuss that some more in the coming days and try and figure out in which different scenarios you might prefer one gem over another.

Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.