Just as we have done with Excel and Word, we can use the win32ole library to automate various tasks in Microsoft Outlook. Let's take a look at how to create an new email message.
Of course, we'll want to require the win32ole library:
Create an instance of the Outlook Application object:
outlook = WIN32OLE.new('Outlook.Application')
Outlook is a single-instance application, so if it is already running, calling the WIN32OLE.new method will behave the same as the WIN32OLE.connect method, returning the running instance.
To create a new item in Outlook, call the Application object's CreateItem method and pass it a numeric value that represents the type of item to create. Valid arguments include:
olMailItem = 0
olAppointmentItem = 1
olContactItem = 2
olTaskItem = 3
olJournalItem = 4
olNoteItem = 5
olPostItem = 6
So, to create a new email message (ie, MailItem), we call the CreateItem method with an argument of 0 (zero):
message = outlook.CreateItem(0)
This returns the newly-created mail item object. We'll proceed by setting values for this MailItem object's properties and calling some of its methods.
To define the subject line of the message, set its Subject value with a string:
message.Subject = 'Double-Header Today'
To define the message body, set the Body value to a string:
message.Body = 'This is the message body.'
Alternatively, for an HTML message body, set the HtmlBody value to an HTML-encoded string.
Define the recipient by setting the To property...
message.To = 'email@example.com'
...or call the Recipients.Add method one or more times:
Got attachments to add? Call the Attachments.Add method one or more times, passing it the path and name of the attachment:
The second argument, 1, indicates that this is an attached file, rather than a link to the original file.
You can save the unsent message in your Outbox by calling the Save method...
This would then allow you to open and review the message before manually clicking the Send button.
Of course, you can send the message with the Send method:
Note that when using the Send method, Outlook may display a security alert that forces the user -- after a forced pause of about five seconds -- to click 'Yes' to allow the message to be sent. I am unaware of a method for avoiding this alert dialog.
UPDATE: I have discovered, but not yet used, a free Outlook add-in from MAPILab that allows the end user to set Outlook security settings. And the related ($99) Security Manager claims to allow you to bypass the Outlook security alerts, with a single line of code. I can't recommend either solution, not having tried them, but mention them here for your information.
That about wraps our show for today. Would you like to see more about Automating Outlook with Ruby? As always, feel free to post a comment here or email me with questions, comments, or suggestions.
Thanks for stopping by!