HOWTO: Send a Message by Outlook Object Model with VC++ID: Q199870
|
This article contains a Microsoft Visual C++ code sample that demonstrates how to send a message using Outlook Object Model.
Before compiling and running the following code, be sure to follow the instructions given wherever the text "TO DO:" is found.
// Change the path to msoutl85.olb if necessary.
#import "C:\\Program Files\\MicrosoftOffice\\Office\\msoutl85.olb"\
no_namespace exclude("_IRecipientControl", "_DRecipientControl")
#include <stdio.h>
#include <tchar.h>
void dump_com_error(_com_error &e)
{
_tprintf(_T("Oops - hit an error!\n"));
_tprintf(_T("\a\tCode = %08lx\n"), e.Error());
_tprintf(_T("\a\tCode meaning = %s\n"), e.ErrorMessage());
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
_tprintf(_T("\a\tSource = %s\n"), (LPCTSTR) bstrSource);
_tprintf(_T("\a\tDescription = %s\n"), (LPCTSTR) bstrDescription);
}
// If this is placed in the scope of the smart pointers, they must be
// explicitly Release(d) before CoUninitialize() is called. If any
// reference count is non-zero, a protection fault will occur.
struct StartOle {
StartOle() { CoInitialize(NULL); }
~StartOle() { CoUninitialize(); }
} _inst_StartOle;
void main()
{
try
{
NameSpacePtr pNameSpace;
MAPIFolderPtr pOutbox;
ItemsPtr pOutboxItems;
_MailItemPtr pNewMail;
AttachmentsPtr pAttachments;
RecipientsPtr pRecipients;
RecipientPtr pRecipient;
// Create an Outlook.Application pointer.
_ApplicationPtr pApp("Outlook.Application");
// Create NameSpace pointer.
pNameSpace = pApp->GetNamespace(L"MAPI");
// If Outlook is not running, uncomment the next line.
//pNameSpace->Logon("TO DO: Place profile name here");
// Create pointer to the Outbox Folder.
pOutbox = pNameSpace->GetDefaultFolder(olFolderOutbox);
// Create pointer to the Messages Collection.
pOutboxItems = pOutbox->Items;
// Create pointer to a new message.
pNewMail = pOutboxItems->Add();
// Set the Subject of the message.
pNewMail->Subject = "New Mail Subject";
// Set the Text of the message.
pNewMail->Body = "New mail body\n";
// Create pointer to the Attachments collection.
pAttachments = pNewMail->Attachments;
// Create new Attachment.
pAttachments->Add("c:\\Autoexec.bat", (long)1, (long)(15000),
"Autoexec.bat");
// Create pointer to Recipients Collection.
pRecipients = pNewMail->Recipients;
// Add recipient.
pRecipients->Add("TO DO: Place email alias here");
// Resolve the recipient address.
pRecipients ->ResolveAll();
// Send the message.
pNewMail->Send();
_tprintf(_T("Message sent\n"));
// Logoff NameSpace.
pNameSpace->Logoff();
}
catch (_com_error &e)
{
dump_com_error(e);
}
}
Additional query words:
Keywords : kbMsg kbOutlook kbOutlook98 kbOutlookObj
Version : WINDOWS:
Platform : WINDOWS
Issue type : kbhowto
Last Reviewed: February 6, 1999