The structure of the Outlook object model 1.31 is shown. The top-level object is Application.
The object can use all other Outlook objects, and the Application is unique and can use CreateOleObject
The Outlook object created by the function. Next, we will talk about the NameSpace object, which provides access to the data source.
In 98, MAPI message storage is the only data source.
The MAPIFolders set corresponds to a group of MAPI folders, that is, a group of MAPIFolder objects. Each MAPIFolder object also contains a Folders set
Each collection also contains an Items set for managing Item objects. Figure 1.32 is a Delphi program that displays
The Folders set and the Items content in the contact directory. The program code is as follows:
Fig 1.32
Procedure TForm1.OpenBtnClick (Sender: TObject );
Var
OutlookApp, Mapi,
Contacts, Personal: Variant;
I: Integer;
Begin
{Get Outlook Application Object}
OutlookApp: = CreateOleObject ('outlook. application ');
{Get MAPI NameSpace object}
Mapi: = OutlookApp. GetNameSpace ('mapi ');
{Traverse the MAPI directory set and add the directory name to the list box}
For I: = 1 to mapi. folders. Count do
Mapilist. Items. Add (mapi. folders (I). Name );
{Retrieve the directory set of the personal folder}
Personal: = mapi. folders ('personal folders ');
{Traverse the directory of the personal folder and add the directory name to the list box}
For I: = 1 to personal. folders. Count do
Personallist. Items. Add (personal. folders (I). Name );
{Retrieve Contact Directory}
Contacts: = personal. folders ('contacts ');
{Retrieve the contact name list in the contact directory}
For I: = 1 to contacts. Items. Count do
Contactslist. Items. Add (contacts. Items (I). fullname );
{Close outlook .}
Outlookapp: = unassigned;
End;
Here we use later binding to call outlook like VB. Createoleobject uses outlook. Application
(Outlook class name) load the outlook server as a parameter call and return a reference to the Application object. You can obtain
References to other outlook objects. The getnamespace method of the Application object will return the namespace object (note that the call parameter is
MAPI ). Through the NameSpace object, the Code traverses the MAPIFolders set and adds the name of each directory to the MapiList list box.
As shown in Figure 1.32, The MAPIFolders set contains a Personal folder, and the code returns the reference to the Personal folder Personal: =
Mapi. Folders
Obtain the name of the person in the directory of all contacts (obtained through the FullName attribute ).
Obviously, to grasp the method of controlling Outlook, we must understand the inheritance relationship of Outlook objects and the attributes, methods, and events of each object. Outlook provides a Help File VBAOUTL. HLP, which includes related information.
The following code shows how to search for a contact directory and copy the content to a database:
Procedure TLoadTableForm. LoadBtnClick (Sender: TObject );
Var
OutlookApp, Mapi,
ContactItems, CurrentContact: Variant;
Begin
OutlookApp: = CreateOleObject ('outlook. application ');
Mapi: = OutlookApp. GetNameSpace ('mapi ');
{Retrieve the Items set of the contact directory}
ContactItems: = Mapi. Folders ('personal Folders '). Folders ('contacts'). Items;
{Loading to database}
With ContactTable do
Begin
EmptyTable;
Open;
DisableControls;
CurrentContact: = ContactItems. Find ('[CompanyName] =' +
QuotedStr ('borland International '));
While not VarIsEmpty (CurrentContact) do
Begin
Insert;
FieldByName ('entryid'). AsString: =
CurrentContact. EntryId;
FieldByName ('lastname'). AsString: =
CurrentContact. LastName;
FieldByName ('firstname'). AsString: =
CurrentContact. FirstName;
FieldByName ('companyname'). AsString: =
CurrentContact. CompanyName;
FieldByName ('busaddrstreet'). AsString: =
CurrentContact. BusinessAddressStreet;
FieldByName ('busaddrpobox'). AsString: =
CurrentContact. BusinessAddressPostOfficeBox;
FieldByName ('busaddrcity'). AsString: =
CurrentContact. BusinessAddressCity;
FieldByName ('busaddrstate'). AsString: =
CurrentContact. BusinessAddressState;
FieldByName ('busaddrpostalcode'). AsString: =
CurrentContact. BusinessAddressPostalCode;
FieldByName ('businessphone'). AsString: =
CurrentContact. BusinessTelephoneNumber;
Post;
CurrentContact: = ContactItems. FindNext;
End; // while
EnableControls;
End; //
{Close Outlook}
OutlookApp: = Unassigned;
End;
The basic steps for running the above Code are the same as those before. The difference is that the Items set of the contact directory is obtained first, and then the Find method is called to locate special Items in the set based on the combination of attributes, for example:
Currentcontact: = contactitems. Find ('[companyName] =' +
Quotedstr ('borland International '));
Is to find the contact whose companyName attribute is Borland International. If no matched contact is found, currentcontact is null. While loop uses findnext to traverse and match contacts, and insert all attributes of contacts into the database.
Creating a new contact directory and record is also very simple. The following code copies all Borland employee contact information to a new directory:
Procedure tcreatefolderfrom. createbtnclick (Sender: tobject );
Const
Olfoldercontacts = 10;
Olcontactitem = 2;
VaR
Outlookapp, mapi,
Newcontact, borlandcontacts,
Contactitems, currentcontact: variant;
I, toremove: integer;
Begin
Outlookapp: = createoleobject ('outlook. application ');
Mapi: = outlookapp. getnamespace ('mapi ');
Contactitems: = mapi. folders ('personal folders '). folders ('contacts'). items;
{Delete test folder}
ToRemove: = 0;
For I: = 1 to Mapi. Folders ('personal Folders '). Folders. Count do
If Mapi. Folders ('personal Folders '). Folders (I). Name = 'borland contacts' then
Begin
ToRemove: = I;
Break;
End; // if
If ToRemove <> 0 then
Mapi. Folders ('personal Folders '). Folders. Remove (ToRemove );
{Create a new folder}
Mapi. Folders ('personal Folders '). Folders. Add ('borland contacts', olFolderContacts );
BorlandContacts: = Mapi. Folders ('personal Folders '). Folders ('borland contacts ');
{Add a contact to a new directory}
CurrentContact: = ContactItems. Find ('[CompanyName] =' +
QuotedStr ('borland International '));
While not VarIsEmpty (CurrentContact) do
Begin
{Add a new project}
Newcontact: = borlandcontacts. Items. Add;
{Set attributes}
Newcontact. fullname: = 'John Doe ';
Newcontact. lastname: = currentcontact. lastname;
Newcontact. firstname: = currentcontact. firstname;
Newcontact. companyName: = currentcontact. companyName;
Newcontact. businessaddressstreet: =
Currentcontact. businessaddressstreet;
Newcontact. businessaddresspostofficebox: =
Currentcontact. businessaddresspostofficebox;
Newcontact. businessaddresscity: =
Currentcontact. businessaddresscity;
Newcontact. businessaddressstate: =
Currentcontact. businessaddressstate;
Newcontact. businessaddresspostalcode: =
Currentcontact. businessaddresspostalcode;
NewContact. BusinessTelephoneNumber: =
CurrentContact. BusinessTelephoneNumber;
{Save record}
NewContact. Save;
{Find the next record in the contact directory}
CurrentContact: = ContactItems. FindNext;
End; // while
OutlookApp: = Unassigned;
End;
The above code flow is to first find the Borland contact directory in the Folders collection.
. Call the Add method of the Folders object to create a new Borland
Contact folder. The Add method requires two parameters: the first is the name of the directory to be created, and the second is the folder type (which can be olFolderCalendar,
OlFolderContacts, olFolderInbox, olFolderJournal, olFolderNotes or
OlFolderTasks type ).
Next, call the Find method of the Items object in the contact directory to locate information records of Borland employees. Call the Add method of the Items object in the newly created Borland contact directory to Add the records found in the contact directory. Finally, call the Save method of the new record to Save the added information.
Other Outlook objects
The Folders set in the personal folder also includes the following Folders: deleted emails, inbox, inbox, sent emails, calendar, diary, notebook, task, and draft.
We can use similar methods to operate the Items of any object.
Set, the difference is that the properties of the Set project are different, the following code demonstrates how to set the full start time of the appointment to greater than 99/04/27, and copy the all-day appointment information to the database
Method. Note that a search expression that is more complex than the previous one is used. The search expression supports the >,<,>=, <=, =, and <> operators, and, or, and
Not logical operator.
Procedure TLoadTableForm. LoadBtnClick (Sender: TObject );
Var
OutlookApp, Mapi,
ApptItems, CurrentAppt: Variant;
Begin
OutlookApp: = CreateOleObject ('outlook. application ');
Mapi: = OutlookApp. GetNameSpace ('mapi ');
PptItems: = Mapi. Folders ('personal Folders '). Folders ('Calendar'). Items;
With ApptTable do
Begin
EmptyTable;
Open;
DisableControls;
CurrentAppt: = ApptItems. Find ('[Start]>' +
"4/27/99" and [AllDayEvent] = true ');
While not VarIsEmpty (CurrentAppt) do
Begin
Insert;
FieldByName ('start'). AsDateTime: = CurrentAppt. Start;
FieldByName ('subobject'). AsString: = CurrentAppt. Subject;
FieldByName ('end'). AsDateTime: = CurrentAppt. End;
FieldByName ('busy'). AsBoolean: = CurrentAppt. BusyStatus;
Post;
CurrentAppt: = ApptItems. FindNext;
End; // while
EnableControls;
End; //
OutlookApp: = Unassigned;
End;
Email Viewer
There is no doubt that the biggest use of Outlook is its mail processing function. through automation, you can easily use the powerful functions of Outlook. Below we will compile a mail viewer. First
Create a new project, and place a TOutLine and TButton on the form. Then declare a TItem class to save the reference to the mail. The class is defined as follows:
TItem = class (TObject)
Letter: OleVariant;
Name: string;
End;
Add the following variables to the public part of the form class declaration:
Public
{Public declarations}
OlApp, NameSpace, root: OleVariant;
List: Tlist;
Item: TItem;
Icount: integer;
End;
Then, initialize the TList in the Oncreate event of the form to maintain the mail list:
Procedure TForm1.FormCreate (Sender: TObject );
Begin
List: = TList. Create;
Item: = TItem. Create;
Icount: = 0;
End;
Then write The onClick event of the Button to create the folder Tree View:
Procedure TForm1.Button1Click (Sender: TObject );
Procedure scan (ol: TOutline; root: OleVariant; s: string );
Var
I, j, k: integer;
Bcount, rcount: integer;
Branch, MAPIFolder: olevariant;
Line: string;
Begin
Line: = '';
Rcount: = root. count;
For I: = 1 to rcount do
Begin
Line: = s + root. item [I]. name;
Ol. Lines. Add (line );
List. Add (TItem. Create );
Item: = List. items [List. count-1];
Item. name: = 'folder ';
Branch: = root. item [I]. folders;
Bcount: = branch. count;
MAPIFolder: = Namespace. GetFolderFromId (root. item [I]. EntryID,
Root. item [I]. StoreID );
If MAPIFolder. Items. count> 0 then
For j: = 1 to MAPIFolder. Items. count do
Begin
Ol. Lines. Add (s + ''+ MAPIFolder. Items [j]. subject );
List. Add (TItem. Create );
Item: = List. items [List. count-1];
Item. name: = 'file ';
Item. Letter: = MAPIFolder. Items [j];
End;
If bcount> 0 then
Begin
Scan (ol, branch, s + '');
End;
End;
End;
Begin
Oline_outlook.Lines.Clear;
OlApp: = CreateOleObject ('outlook. application ');
Namespace: = OlApp. GetNameSpace ('mapi ');
Root: = Namespace. folders;
Scan (oline_outlook, root ,'');
End;
First, obtain the folder set, Scan each sub-folder in the for loop, and add information. If there are sub-directories, recursively call:
If bcount> 0 then
Begin
Scan (ol, branch, s + '');
End;
When double-clicking, You need to display the mail content, write the OutLine doubleClick event, and use Showmessage to display the mail content:
Procedure TForm1.oLine _ OutLookDblClick (Sender: TObject );
Begin
Item: = List. items [oline_outlook.SelectedItem-1];
// Body content
If Item. name = 'file' then ShowMessage (Item. Letter. Body );
End;
Finally, you cannot forget to release resources when you exit the program. Compile the OnCloseQuery event processing function of the form:
Procedure TForm1.FormCloseQuery (Sender: TObject; var CanClose: Boolean );
Var
I: integer;
Begin
For I: = List. Count-1 downto 0 do
Begin
Item: = List. Items [I];
Fig 1.33
Item. Free;
End;
List. Free;
End;
The final program running result 1.33 is shown.
Send email
The following code demonstrates how to send an email with an attachment:
Const
OlByValue = 1;
Olbyreference = 4;
Olembeddeditem = 5;
Olole = 6;
Olmailitem = 0;
Olappointmentitem = 1;
Olcontactitem = 2;
Oltaskitem = 3;
Oljournalitem = 4;
Olnoteitem = 5;
Olpostitem = 6;
Olfolderdeleteditems = 3;
Olfolderoutbox = 4;
Olfoldersentmail = 5;
Olfolderinbox = 6;
Olfoldercalendar = 9;
Olfoldercontacts = 10;
Olfolderjournal = 11;
Olfoldernotes = 12;
Olfoldertasks = 13;
Function sendmailwithattachments (email, Subject: string; body: widestring; filename: string): Boolean;
VaR
Outlook: variant;
Item: variant;
Begin
Try
Outlook: = CreateOLEObject ('outlook. application ');
Try
Item: = outlook. CreateItem (olMailItem );
Item. Subject: = Subject;
Item. Body: = Body;
Item. Attachments. Add (FileName, 1,1, FileName );
Item. To: = email;
Item. Send;
Finally
// Make sure that Outlook is not enabled
Outlook. quit;
End;
Except
Result: = false;
Exit;
End;
Result: = true;
End;
Function usage:
SendMailWithAttachments ('info @ outlook.com ', 'sendmail function', 'test! ', 'D:/test.doc ');
Note that we use CreateItem to create a mail project. constants such as olMailItem are copied from the help of office.
Back up attachments in the email
The following function backs up the corresponding attachments to the specified directory based on the sender name or mail address, and deletes the corresponding emails according to the input parameter MailDelete:
Function ManageAttachments (SendersName, AttachmentPath: string; MailDelete: boolean): boolean;
Var
OApp: variant;
ONs: variant;
OFolder: variant;
OMsg: variant;
AtC: variant;
AttFilename: variant;
Filename: string;
CheckSender: string;
Counter: integer;
MailCounter: integer;
Begin
Try
OApp: = CreateOLEObject ('outlook. application ');
Try
ONs: = oApp. GetNamespace ('mapi ');
// Inbox
Ofolder: = oNS. GetDefaultFolder (olFolderInbox );
MailCounter: = 1;
// If an email is in the inbox
If ofolder. Items. Count> 0 then
Begin
Repeat
// Obtain the first region
Omsg: = ofolder. Items (mailcounter );
// Check the sender's name or address
If checksender = sendersname then
Begin
// Check the number of Attachments
ATC: = omsg. attachments. count;
If ATC> 0 then
Begin
// Save all attachments
For counter: = 1 to ATC do
Begin
Attfilename: = omsg. attachments. Item (Counter). filename;
Filename: = ncludetrailingbackslash (attachmentpath) + attfilename;
Omsg. attachments. Item (Counter). saveasfile (filename );
End;
End;
If MailDelete then
Begin
OMsg. delete;
Dec (MailCounter );
End;
End;
// Obtain the next letter
Inc (MailCounter );
Until MailCounter> ofolder. items. count;
End;
Finally
OApp. quit;
End;
Except
Result: = false;
Exit;
End;
Result: = true;
End;
Usage:
ManageAttachments ('info @ outlook.com ', 'f:/test', false );
Conclusion
After a clear understanding of the Outlook object system, we can automatically and easily control Outlook to extract information, add new users, send mail information, and other powerful functions.