Thursday, August 03, 2006

Ruby script to send email with authentication and attachments

Here's a little script I wrote to send email in Ruby with smtp authentication and attachments, it needs tmail(included in Rails). It could obviously use more polish, I wrote it based on some samples in tmail, unfortunately the tmail docs are little lacking. Since I wrote it on linux/mac, moving it to windows was little tricky because Tmail ruby library includes c-code that needs to be compiled. However the rails package active_mailer includes tmail (I am not quite sure if it is exact same version as on the Tmail page), so I just had to figure out to require rubygems and active_mailer on windows in addition to Tmail.
Also as usual I got stuck for a while with the attachments on windows, since as usual I forgot the idiotic behavior on windows where attachment files such as docs or images need to be opened with "rb" flags to indicate binary file(not necessary on Unix like Linux and Mac), otherwise it won't error, but it will just truncate the file.

Now this can handle arbitrary number of attachments and you can put in toList things like in
#--tolist="toListProd.txt"
cc:
bcc
#and commments

Anyway here is the version that works on windows, for linux just remove the items mentioned above:
http://maanpaa.blogspot.com/2006/08/ruby-email-with-authentication-and.html

4 Comments:

Anonymous Anonymous said...

Hi Ville,
I found your blog while googling 'ruby smtp'. Your ruby script from nails worked very nicely on blue-two. I am not sure why the version from yawl wouldn't work on blue-two. The only other issue I had was when trying to execute the email script inside ruby code. For some reason I kept getting a strange 'Exec format error'. I decided it would be nice to be able to run this script as a module as well as standalone so I added a small tweak:

...

def mail(subject="", tolist="", data2="", attach1="")
attachments = []
to = []
attachments << attach1
smtphost = 'imap.nexatech.com'
from = 'build@nexatech.com'

if FileTest.exists?(tolist)
File.open(tolist, "r") do |f|
f.each_line { |line| to << line }
end
end
send_mail smtphost, setup_mail(from, to, subject, data2, attachments)
end

...

if __FILE__ == $0
main
end

8/16/2007 04:16:00 PM  
Anonymous Anonymous said...

I don't see the script (or a link to it) in your post.

9/25/2007 09:11:00 PM  
Blogger TTE&V said...

This comment has been removed by the author.

9/27/2007 07:59:00 AM  
Blogger TTE&V said...

The script is here:
http://maanpaa.blogspot.com/2006/08/ruby-email-with-authentication-and.html

9/27/2007 08:00:00 AM  

Post a Comment

<< Home