As you have already learned, Outlook is the application in Office that manages e-mail, appointments, contact information, and other tasks related to scheduling and communicating in the workplace. Outlook doesn't contain its own Visual Basic Editor for building macros, but it does have an object library that you can use to run its commands from other Office macros.
In this section, you'll see how to send e-mail via Outlook from within a Word macro named SendMail. Before you create the SendMail macro, you'll need to edit the code in the Command1_Click event procedure to use e-mail names that fit your particular situation. Don't use the ones shown, because they're not real— you'll get an error back from your e-mail service provider if you try them. If you want to send a sample attachment, you'll also need to place the Guitar.bmp file in your root folder (C:\) or substitute a different pathname in the code.
ON THE WEB
The SendMail macro is located in the Chap62 document on the Running Office Reader's Corner page. The Guitar.bmp file (required as an attachment) is also on the Reader's Corner page.
Follow these steps to create the macro:
Visual Basic adds the Office object library to your project.
Set out = CreateObject("Outlook.Application") With out.CreateItem(olMailItem) 'using the Outlook object 'insert recipients one at a time with the Add method '(these names are fictitious -- replace with your own) .Recipients.Add "maria@xyz.com" ''To: field .Recipients.Add "casey@aaa.com"" 'To: field .Subject = "Test Message" 'include a subject field .Body = Selection.Text 'copy selected text for message 'insert attachments one at a time with the Add method .Attachments.Add "c:\guitar.bmp" 'finally, copy message to Outlook outbox with Send .Send End With |
Follow these steps to run the macro and send electronic mail via Outlook:
You'll want to verify that Visual Basic puts the e-mail message in Outlook's Outbox folder.
Visual Basic uses Automation to create a mail message in the Outlook Outbox folder. The message will remain in Outlook's Outbox folder until you connect to your e-mail service and choose Check For New Mail from the Outlook Tools menu.
You'll see a pending mail message, as shown in the following illustration:
Outlook opens the message and displays it on the screen. (See Figure 41-2.) As you can see, Word sent the message exactly as you directed, complete with a guitar attachment, if you downloaded it from the Web to your root folder.
You're finished working with Outlook in this chapter.
Figure 41-2. This Outlook mail message was created by Word's SendMail macro.