What's the easiest way to send a message through Outlook with Ruby?
Asked Answered
E

2

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.

Elocution answered 26/9, 2012 at 0:58 Comment(0)
H
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 '[email protected]'
message.Recipients.Add '[email protected]'
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".

Hillman answered 26/9, 2012 at 1:9 Comment(3)
I had never heard of win32ole. I went looking for some resources and found this: #1326803 -- However, there has been no update on the book in 3 years. Do you know of any more documentation?Kyd
Well [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 has been my goto for quick and dirty usability tutorials.Hillman
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...Spine
J
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.

Jitters answered 27/11, 2013 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.