5

My work requires me to automate e-mail generation for certain tests. I've been looking around but havent been able to find a reasonable solution that can be implemented quickly. It needs to be in outlook and not some other mail server as we have some strange authentication rules in place, and we need the option of saving drafts instead of just sending the message.

Apparently win32ole can do this, but I can't find any reasonably simple examples.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303

2 Answers2

9

Assuming that the Outlook credentials are stored and you are set to autologin to Outlook, WIN32OLE does the trick quite nicely:

require 'win32ole'
outlook = WIN32OLE.new('Outlook.Application')
message = outlook.CreateItem(0)
message.Subject = "Hey look a subject!"
message.Body = "Yes this is dog"
message.Recipients.Add 'dog@dog.com'
message.Recipients.Add 'cat@dog.com'
message.Attachments.Add('C:\Path\To\File.txt')
#Want to save as a draft?
message.Save
#Want to send instead?
message.Send

This is in fact quite well documented in "Automating Outlook with Ruby: Saving Mail Messages To Files", as is automating the rest of windows with Ruby.

You may have an authorization issue, which, if it appears, can be solved using "Advanced Security for Outlook".

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Tadgh
  • 1,999
  • 10
  • 23
  • I had never heard of win32ole. I went looking for some resources and found this: http://stackoverflow.com/questions/1326303/any-standard-guide-for-ruby-win32ole-api -- However, there has been no update on the book in 3 years. Do you know of any more documentation? – sunnyrjuneja Sep 26 '12 at 02:04
  • Well [http://www.ruby-doc.org/stdlib-1.9.3/libdoc/win32ole/rdoc/WIN32OLE.html] are the official ruby docs I think. Other than that, [ruby on windows](http://rubyonwindows.blogspot.ca/) has been my goto for quick and dirty usability tutorials. – Tadgh Sep 26 '12 at 02:13
  • For some reason I had to invoke send directly using `msg._invoke(msg.ole_methods.select {|m| m.name=="Send"}[0].dispid,[],[])` not sure why, but there you go... – Sancarn Mar 12 '19 at 12:56
0

If the Outlook account has web access (via outlook.com or office365.com) you can also use Mikel Lindsaar's Ruby email library. It works well for many different email providers that allow POP3, IMAP4, or SMTP connections.

I posted an entry with some sample code on sending and receiving Outlook email via Ruby that might help. Sorry, I can't comment on how to save drafts, though.

jantony_pdx
  • 83
  • 2
  • 9