In this chapter, you'll learn how to use the MAPI controls from Visual Basic to create a simple program that can read and reply to all e-mail sent to the logon ID. You'll also learn how to write routines to access all the electronic mail services available to a basic MAPI client application on a desktop workstation. This includes creating new e-mail messages, checking the inbox for new mail, and accessing and updating the e-mail address book. When you complete this chapter, you will have a fully functional e-mail client application.
You'll also learn the details of using the MAPISession and MAPIMessage controls with Visual Basic 4.0. The Visual Basic MAPI controls offer a quick way to build Simple MAPI applications. The MAPI controls allow you full access to the Inbox object, to the MAPI Compose, Fetch, Read, Delete, and Send services, and limited access to the address book.
Note |
Simple MAPI is sometimes called MAPI 0 to indicate that it precedes the MAPI 1.0 release that matches Microsoft Exchange Server. Throughout this book, you'll see Simple MAPI instead of MAPI 0. |
When you complete the coding examples in this chapter, you will understand the basics of Simple MAPI, and you'll know how to use Visual Basic and the MAPI controls to read, compose, address, send, and delete MAPI messages.
Note |
Throughout the rest of this chapter, there are sample programs that illustrate the use of the MAPI controls to create mail-aware applications with Visual Basic 4.0. These programs must be run on a workstation that has access to simple MAPI services through a MAPI-compliant mail server. MAPI-compatible servers from Microsoft include the Microsoft Mail Server for DOS, Microsoft Exchange Server for NT, Microsoft Mail for Windows for Workgroups, Windows 95 Exchange Mail, or any other fully MAPI-compliant system (such as WordPerfect Office). |
Visual Basic 4.0 Professional Edition ships with two OCX controls that provide access to all the MAPI services you'll need to create fully functional electronic mail applications using Visual Basic. The MAPISession control provides access to everything you'll need to sign on and sign off any MAPI-compliant server. The MAPIMessage control provides access to the MAPI routines that allow you to read, compose, address, and send messages using the session established with the MAPISession control. This section of the chapter will review the MAPI-related properties and methods of each of these controls.
The MAPISession control is used to establish a link between your Visual Basic program (the mail client) and the electronic mail server. The MAPI-compliant mail server must be installed and available to the Visual Basic client program. If your program will run on a traditional network server, the mail server may be Microsoft Mail installed on a network workstation. If you are running Windows for Workgroups or Windows 95, Microsoft Mail or Microsoft Exchange can act as a mail server. There are other mail servers available for both file server and peer-to-peer networks.
There are two methods and seven properties for the MAPISession control that are directly MAPI related. The two following sections identify these components of the MAPISession control, and describe their meaning and their use in Visual Basic programs.
There are only two MAPISession methods: SignOn and SignOff. The SignOn method is used to begin a MAPI session. By default, the SignOn method provides a logon dialog box that prompts the user for valid logon information. The exact nature of the logon dialog box depends on the mail server. The Microsoft Mail logon dialog box prompts the user for a valid username and password (see Figure 7.1).
Figure 7.1 : Default logon dialog box for Microsoft Mail.
The default logon dialog box for the Microsoft Exchange Mail product simply asks the user to select the desired mail services profile (see Figure 7.2).
Figure 7.2 : Default logon dialog box for Microsoft Exchange Mail.
If a valid username and password are supplied by way of the SignOn method, the MAPISession control returns a unique value in the SessionID property. This unique value is used in all message transactions to identify the link between the client application and the mail server. We'll talk more about the SessionID property in the next section of this chapter.
The SignOff method of the MAPISession control does just what you'd expect-it safely ends your link to the mail server. There is no dialog box associated with the SignOff method.
In order to use the MAPISession control methods, you must first place the MAPISession control on a Visual Basic form. The form is invisible at run-time and is only used to provide the methods and properties needed to establish a MAPI session between your Visual Basic program and the mail server.
As an example of the MAPISession control, start a Visual Basic project. Use the Tools | Custom Controls menu item to add the Microsoft MAPI controls to your project. Place a MAPISession control on the form and add the three lines of code in Listing 7.1 to the Form_Load event.
Listing 7.1. A tiny e-mail client.
Private Sub Form_Load()
'
MAPISession1.SignOn
MAPISession1.SignOff
End
'
End Sub
Save the form as CDG0701.FRM and the project as CDG0701.VBP, and run the project. You'll see the default logon dialog box provided by your mail server. Once you sign in, the Visual Basic program immediately signs you out and ends. You'll add more features as we go along.
The MAPISession control has seven MAPI-related properties. These properties all deal with options that you can set to control the behavior of the control at logon time.
The Action property can be used to invoke the sign-on or sign-off methods. This property was present in Visual Basic 3.0 and has been replaced by the SignOn and SignOff methods discussed earlier.
The DownloadMail property is used to control whether new messages are downloaded from the mail server at logon time. By default, all new messages are forced into the user's mailbox at logon time. You can set this property to False to prevent this from happening. In the code example in Listing 7.2, the DownloadMail property has be set to False before invoking the SignOn method.
Listing 7.2. Setting the DownloadMail property of the MAPISession control.
Private Sub Form_Load()
'
MAPISession1.DownloadMail = False ' don't get new mail
MAPISession1.SignOn
MAPISession1.SignOff
End
'
End Sub
The LogonUI property can be used to turn off the default logon screen provided by the mail server. You can set this property to False to suppress the mail server from presenting the logon screen when you invoke the SignOn method. If you set this property to False, you must supply valid data in the UserName and Password properties, or an error will be reported.
You can use the NewSession property to force the creation of a new MAPI session, even if a MAPI session already exists for this workstation. By default, the SignOn method will attempt to locate any current MAPI interface sessions before attempting to log on to the mail server. When you set the NewSession parameter to True, the SignOn method will create a second MAPI session link with the mail server. The code in Listing 7.3 shows how this is done.
Listing 7.3. Setting the NewSession property of the MAPISession control.
Private Sub Form_Load()
'
MAPISession1.DownloadMail = False ' dont get new mail
MAPISession1.NewSession = True ' force a new session
MAPISession1.SignOn
MAPISession1.SignOff
End
'
End Sub
The Password and UserName properties should be set to valid values if you want to bypass the default logon screen. If you supply a UserName but leave the Password property blank, the SignOn method will force the logon dialog box to appear and prompt for the missing information. If, however, the LogonUI property is set to False, no dialog box will appear, and an error will be returned.
If you are using the Microsoft Exchange Mail Client, you only need to provide a valid Profile Name. Microsoft Exchange Mail will ignore any value in the Password property. If you are using the Microsoft Mail client (network or workgroup version), you will need to supply both the UserName and the Password properties if you want to bypass the default logon dialog box. Refer to Listing 7.4 for an example.
Listing 7.4. Getting the username and password at sign-on.
Private Sub Form_Load()
'
MAPISession1.DownloadMail = False ' don't get new mail
MAPISession1.NewSession = True ' force a new session
MAPISession1.UserName = "MCA" ' username for mail
MAPISession1.Password = "PASSWORD" ' users password
MAPISession1.SignOn
MAPISession1.SignOff
End
'
End Sub
The SessionID property is a read-only property available only at run-time that contains the unique session ID number of a completed link between your Visual Basic program and the mail server. This session ID value must be used in all transactions to the mail server. Its value is used to set the SessionID of the MAPIMessage control before attempting to access the message services provided by the mail server. The code in Listing 7.5 displays the value of the SessionID after a successful logon of the user.
Listing 7.5. Displaying the SessionID property.
Private Sub Form_Load()
'
MAPISession1.DownloadMail = False ' dont get new mail
MAPISession1.NewSession = True ' force a new session
MAPISession1.UserName = "VBU Profile" ' username for mail
MAPISession1.Password = "" ' user password
MAPISession1.SignOn
MsgBox Str(MAPISession1.SessionID) ' show unique session handle
MAPISession1.SignOff
End
'
End Sub
Modify the UserName and, if needed, the Password properties to contain valid logon data for your mail server. Then save and run the project. You will see a message box that shows the unique session handle for the MAPI session (see Figure 7.3).
Figure 7.3 : Displaying the SessionID of a MAPI session.
The MAPIMessage control gives your Visual Basic program access to all the message services available from the mail server with which your program has established a session. The MAPIMessage control provides services for reading, composing, addressing, and sending mail messages. You can perform all major mail operations by requesting the service from the server.
The MAPIMessage control has four primary functions:
There are 11 methods and over 30 properties of the MAPIMessage control that are MAPI-related. We'll review these methods and properties briefly. You can find additional documentation on each of the MAPIMessage properties in the Visual Basic online help files.
There are 11 methods for the MAPIMessage control:
The message-creation methods account for six of the eleven methods. Of these six, you only need to know two before you can create a functional e-mail application. The Compose method clears out the edit buffer area and prepares a clean slate for the creation of a new message. The Send method attempts to send the new message to the address supplied. If an address or message is not supplied, the Send method forces the mail server to present the default message compose form to the user.
In other words, you can create a complete e-mail composer by adding only two lines to the code we started earlier in this chapter. The code shown in the following listing is all you need to create a Visual Basic application that can compose and send e-mail messages. Start a new Visual Basic project and add the MAPISession and the MAPIMessage controls to the form. Then add the code shown in Listing 7.6 to the Form_Load event.
Listing 7.6. Creating a MAPIMessage.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Compose ' clear buffers
Listing 7.6. continued
MAPIMessages1.Send True ' show default form
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
Now save the form as CDG0702.FRM and the project as CDG0702.VBP, and run the program. You'll be prompted for a logon, and then you'll see the default compose form. Figure 7.4 shows what comes up if you are using Microsoft Exchange Mail.
Figure 7.4 : The default compose form for Microsoft Exchange.
Notice that you have a highly functional e-mail program with very little coding. Use this form to send yourself a message. We'll use other Visual Basic code to read the message later in this chapter.
You can use the other message creation methods (Copy, Forward, Reply, and ReplyAll) to load the compose buffer with messages that have been sent to you by others. You can then use the default compose dialog box to edit the old message and send it just as you would a new message you created from scratch. The Forward, Reply, and ReplyAll methods also alter the subject line to reflect the action. For example, when you use the Forward method, the mail server will add "FW:" to the beginning of the subject line. The Reply methods place "RE:" at the start of the subject line.
The code example in Listing 7.7 takes the first message in the user's inbox and copies it to the compose buffer with "FW:" on the subject line.
Listing 7.7. Forwarding a message.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Fetch ' get messages
MAPIMessages1.Forward ' forward the current message
MAPIMessages1.Send True ' send it
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
You can use the Fetch method to tell the mail server to send your Visual Basic program all the messages that are currently on file in the inbox for the logged-on user. The code example shown in Listing 7.8 fetches all the messages for the user and then uses the MsgCount property to find out how many messages are actually on file.
Listing 7.8. Displaying the MsgCount property.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Fetch ' get all messages into inbox
MsgBox Str(MAPIMessages1.MsgCount) ' show number of msgs
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
You can use the Delete method to remove messages from the user's collection. The Delete method can also be used to remove a single recipient from a list of addresses or to remove a single attachment from a list of currently attached files. The code in Listing 7.9 removes the current message from the user's collection.
Listing 7.9. Deleting a message from the user's storage.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Fetch ' get all messages into inbox
MsgBox Str(MAPIMessages1.MsgCount)
MAPIMessages1.Delete ' get rid of first message
MsgBox Str(MAPIMessages1.MsgCount)
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
Finally, you can tell the mail server to show you a list of all the mail server addresses on file by invoking the Show method. The Show method can also be used to display details of the current message recipient (if this is supported by the MAPI mail server). The example code shown in Listing 7.10 will display the current mail server address list.
Listing 7.10. Showing the MAPI address book.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Show ' show the addresss list
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
The MAPIMessage control has more than thirty MAPI-related properties. We will quickly review them here. You can find more detailed information on each of the MAPIMessage control properties by consulting the topic "MAPIMessage Control" in the Visual Basic online help file.
The MAPIMessage control properties
can be divided into several groups. Each group contains a set
of properties that all deal with the same aspect of the message
services provided by the mail server. Table 7.1 shows the MAPI-related
properties, divided by service group.
Group | Property | Description |
Address | AddressCaption | Allows you to set the caption of the Address Book dialog box. |
AddressEditFieldCount | Use this property to set the number of edit buttons available on the Address Book dialog box. | |
AddressLabel | If you use only one edit button (To:), you can set the button label with this property. | |
AddressModifiable | When set to True, allows user to modify the contents of the address book; the default is False. | |
AddressResolveUI | When set to True, presents a dialog box to help users resolve rejected addresses. Use this property in conjunction with the ResolveName method. The default is False. | |
Attachment | AttachmentCount | Contains the number of attachments for the current message. |
AttachmentIndex | Pointer to the current attachment in the list. | |
AttachmentName | Filename of the attachment pointed to by the AttachmentIndex property. | |
AttachmentPathName | Contains full pathname of the current attachment. | |
AttachmentPosition | Position (in characters) where the attachment is located within the message body. | |
AttachmentType | Indicates the type of the current attachment. Valid values are DATA (data file), EOLE (embedded OLE object), and SOLE (static OLE object). | |
Fetch | FetchMsgType | Contains the type of message to look for when executing the Fetch method. Not commonly used by current products. |
FetchSorted | Controls sort order when building message collection. Set to True for First In, First Out sort order. Set to False to sort by user's InBox setting. The default is False. | |
FetchUnreadOnly | Set to True to get only the unread messages into the user's collection. If False, all messages for the user's ID are loaded into the local set. The default is True. | |
Message | MsgConversationID | Contains internally generated ID that keeps track of all messages in a related "thread." You can use this value to collect all related messages into a single group. |
MsgCount | Contains the total number of messages in the set. | |
MsgDateReceived | Date the current message was received. | |
MsgID | Internally generated unique ID value. | |
MsgIndex | Pointer to the current message in the message collection. | |
MsgNoteText | This is the actual body of the message (less any attachments). | |
MsgOrigAddress | Address of the originator (sender) of the current message. | |
MsgOrigDisplayName | Contains the display name associated with the MsgOrigAddress property. | |
MsgRead | Flag to indicate that the message has been read by the user to whom it was addressed. When set to True, the user has read the message. | |
MsgReceiptRequested | Flag to indicate that a return receipt has been requested by the sender. When set to True, the sender wants a confirmation that the message has been successfully delivered. | |
MsgSent | Flag to show that the message has been sent to the mail server for delivery. This flag is updated by the server, not the client. | |
MsgSubject | The text line that identifies the subject of the message. | |
MsgType | Contains the message type code. Currently, all MsgType codes are left null or empty to indicate an Interpersonal Message (IPM). | |
Recipient | RecipAddress | Address of the current recipient (could be a list). |
RecipCount | Contains the number of recipients for the current piece of mail. | |
RecipDisplayName | The display name associated with an address in the address book. | |
RecipIndex | Points to the current recipient in the list. | |
RecipType | Shows what type of recipient is currently pointed to by the RecipIndex property. A value of 0 = OrigList (used only by the message editor); 1 = ToList (a person in a "To" address list); 2 = CcList (a person on the courtesy copy list); 3 = BccList (a person on the blind courtesy copy list). | |
Other | Action | Carryover from Visual Basic 3.0-use the new methods instead. |
SessionID | Contains the value of the SessionID generated by the MAPISession control. You must update this property before you can perform any Message operations. |
You can use these properties to modify the behavior of the MAPI dialog boxes supplied by the mail server. For example, you can change the caption of the address list, change the number of buttons that appear on the list, even change the caption of the To: button. You can also use these properties to add increased functionality to your Visual Basic mail applications by honoring attached documents, allowing the use of blind courtesy copy recipients, and so on.
While there are a number of things you can do with the numerous properties of the MAPIMessage control, one of the most useful is the ability to create e-mail attachments. That is the subject of the next section.
Creating e-mail attachments is very useful and very easy to do with the MAPIMessage control and Visual Basic. Attachments can be simple text files, word processing documents, or even databases. For the next example, you'll attach a system file from a user's workstation and prepare a message to send to the help desk at a large corporation.
There are four property values you need to set in order to successfully create an e-mail attachment:
Note |
If you plan on adding multiple attachments to the message, you'll also need to use the AttachmentCount and AttachmentIndex properties to fetch the attachments when you read the message. |
You can add an attachment to any valid message in the compose buffer. The code example below creates a new message and adds the workstation's CONFIG.SYS file as an attachment. Modify the Form_Load event of CDG0702.FRM to match the code in Listing 7.11.
Listing 7.11. Creating an e-mail attachment.
Private Sub Form_Load()
'
MAPISession1.SignOn ' log into MAPI server
MAPIMessages1.SessionID = MAPISession1.SessionID
'
MAPIMessages1.Compose ' clear buffer
MAPIMessages1.MsgSubject = "User's CONFIG.SYS File"
MAPIMessages1.MsgNoteText = "Here is the CONFIG.SYS File" + Chr(13) + " "
'
MAPIMessages1.AttachmentPosition = Len(MAPIMessages1.MsgNoteText)
MAPIMessages1.AttachmentType = mapData
MAPIMessages1.AttachmentName = "System Configuration File"
MAPIMessages1.AttachmentPathName = "C:\CONFIG.SYS"
'
MAPIMessages1.Send True ' send it
'
MAPISession1.SignOff ' exit MAPI server
End
'
End Sub
Now save and run the CDG0702.VBP project. After logging onto the mail server, you'll see a form appear with the C:\CONFIG.SYS file already attached to the message (see Figure 7.5).
Figure 7.5 : Viewing an added attachment to the message.
The rest of this chapter covers the creation of a complete e-mail client for Simple MAPI access. This example uses all of the default MAPI services supplied by the installed MAPI service provider. The look and feel of the sign-in dialog box, the compose form, and the address book are completely controlled by the underlying MAPI engine running on the workstation. As you saw earlier in the chapter, each of these forms looks different depending on whether you are running Microsoft Mail, Microsoft Exchange, or any other MAPI-compliant messaging provider (such as Perfect Office). By using the services already available on the workstation, you can reduce your coding and maintain a familiar look and feel for your users' e-mail applications.
You will notice that one of the services unavailable within this client is the ability to store and retrieve old messages within the existing private and public mail folders. Simple MAPI services do not include access to the message store. You can only read information from the inbox using Simple MAPI. The Send method automatically writes messages to the outbox, but the Simple MAPI client cannot view messages in the outbox once they are placed there.
Note |
The ability to access mail folders is available through MAPI OLE Messaging. You'll learn how to use OLE Messaging in Chapter 8, "The OLE Messaging Library." |
The simple mail client project requires two forms. The first form (MAPIMAIN.FRM) is the main form in the application. This form will consist of a single list box that shows all the messages in the user's e-mail inbox and a set of command buttons that can be used to perform e-mail activities such as creating new messages, reading e-mail, deleting old messages, saving messages to text files, and replying to existing messages. This form will also hold the MAPI controls and a common dialog box control that will be used to save e-mail messages as text files. Refer to Figure 7.6 when laying out the form.
Figure 7.6 : Laying out the e-mail forms.
Listing 7.12 shows the Visual Basic form code for MAPIMAIN.FRM. When you build the MAPIMAIN.FRM, be sure to add the picture control first; then add a single command button to the form by selecting the command button from the toolbox and drawing it onto the picture control rather than double-clicking the command button from the toolbox. By drawing it on the picture control, you establish the command button as a child control of the picture box. Now, whenever you move the picture box, the command button will move with it.
Listing 7.12. The MAPIMAIN.FRM layout code.
VERSION 4.00
Begin VB.Form MapiMain
Caption = "Form1"
ClientHeight = 1710
ClientLeft = 1875
ClientTop = 1725
ClientWidth = 6345
Height = 2115
Left = 1815
LinkTopic = "Form1"
ScaleHeight = 1710
ScaleWidth = 6345
Top = 1380
Width = 6465
Begin VB.ListBox List1
BeginProperty Font
name = "Courier"
charset = 0
weight = 400
size = 9.75
underline = 0 'False
italic = 0 'False
strikethrough = 0 'False
EndProperty
Height = 840
Left = 120
TabIndex = 1
Top = 540
Width = 4695
End
Begin VB.PictureBox Picture1
Align = 1 'Align Top
Height = 375
Left = 0
ScaleHeight = 315
ScaleWidth = 6285
TabIndex = 0
Top = 0
Width = 6345
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 9
Left = 900
TabIndex = 11
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 8
Left = 1380
TabIndex = 10
Top = 60
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 7
Left = 1800
TabIndex = 9
Top = 60
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 6
Left = 2280
TabIndex = 8
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 5
Left = 2820
TabIndex = 7
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 4
Left = 540
TabIndex = 6
Top = 0
Width = 375
End
Listing 7.12. continued
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 3
Left = 3240
TabIndex = 5
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 2
Left = 3720
TabIndex = 4
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 1
Left = 4200
TabIndex = 3
Top = 0
Width = 375
End
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 315
Index = 0
Left = 120
TabIndex = 2
Top = 0
Width = 375
End
End
Begin MSComDlg.CommonDialog CommonDialog1
Left = 5280
Top = 900
_Version = 65536
_ExtentX = 847
_ExtentY = 847
_StockProps = 0
End
Begin MSMAPI.MAPISession MAPISession1
Left = 5880
Top = 540
_Version = 65536
_ExtentX = 741
_ExtentY = 741
_StockProps = 0
End
Begin MSMAPI.MAPIMessages MAPIMessages1
Left = 5100
Top = 480
_Version = 65536
_ExtentX = 741
_ExtentY = 741
_StockProps = 0
End
End
Also, you'll notice that the command buttons are in the form of a control array. Control arrays are easier to work with than a set of individually named controls. Control arrays also consume fewer Windows resources than a set of individually named controls. You create the array by clicking on the first command button and setting its Index property to 0. Then highlight the control and select Edit | Copy from the Visual Basic main menu. Select Edit | Paste from the same menu. You'll see a dialog box asking you to confirm that you want to create a control array-click Yes. Visual Basic will then place a copy of the control on the form. Continue cutting and pasting until you have ten command buttons in the picture control.
The second form (MAPIREAD.FRM) will be used to display messages sent to you by other users. This form will have a label control to display the e-mail header information, a text box control to display the actual body of the message, and a single command button to close the form. Use the Visual Basic form code in Listing 7.13 and Figure 7.6 as a reference when building the MAPIREAD.FRM.
Listing 7.13. The MAPIREAD.FRM control table.
Begin VB.Form MapiRead
Caption = "Form2"
ClientHeight = 4575
ClientLeft = 1140
ClientTop = 1515
ClientWidth = 6690
Height = 4980
Left = 1080
LinkTopic = "Form2"
ScaleHeight = 4575
ScaleWidth = 6690
Top = 1170
Width = 6810
Begin VB.CommandButton cmdClose
Caption = "&Close"
Height = 495
Left = 5340
TabIndex = 2
Top = 3900
Width = 1215
End
Begin VB.TextBox Text1
Height = 2415
Left = 120
MultiLine = -1 'True
ScrollBars = 2 'Vertical
TabIndex = 1
Listing 7.13. continued
Text = "MapiRead.frx":0000
Top = 1320
Width = 6435
End
Begin VB.Label Label1
BorderStyle = 1 'Fixed Single
Caption = "Label1"
BeginProperty Font
name = "MS LineDraw"
charset = 2
weight = 400
size = 9.75
underline = 0 'False
italic = 0 'False
strikethrough = 0 'False
EndProperty
Height = 1215
Left = 120
TabIndex = 0
Top = 60
Width = 6435
End
End
There are four support routines that you need to add to the MAPIMAIN.FRM form. The first routine, AdjustForm (see Listing 7.14), will do all the work to set the proper size and location for all the controls on the form, including the ten command buttons.
Listing 7.14. Coding the AdjustForm routine.
Public Sub AdjustForm()
'
' set tool bar buttons
'
Dim x As Integer
Dim cBtnCaption(9) As String
'
cBtnCaption(0) = "&Read"
cBtnCaption(1) = "&New"
cBtnCaption(2) = "&Save"
cBtnCaption(3) = "&Del"
cBtnCaption(4) = "&Addr"
cBtnCaption(5) = "&Fwd"
cBtnCaption(6) = "&Reply"
cBtnCaption(7) = "A&ll"
cBtnCaption(8) = "&InBox"
cBtnCaption(9) = "E&xit"
'
For x = 0 To 9
Command1(x).Caption = cBtnCaption(x)
Command1(x).Width = (Picture1.Width / 10) * 0.9
Command1(x).Height = 300
Command1(x).Top = 0
Command1(x).Left = (x * (Picture1.Width / 10))
Next x
'
Picture1.Height = 360
'
' set list box dimensions
'
List1.Left = 120
List1.Width = Me.Width - 360
List1.Top = Picture1.Height + 120
List1.Height = Me.Height - (List1.Top + 600)
'
End Sub
This routine is called at the very start of the program and also each time the user resizes the form during run-time. When you add this routine to the Form_Resize event, all controls will be adjusted automatically each time the user changes the size of the form.
The next support routine you need to add is the MAPIStart routine (see Listing 7.15). This is the routine that attempts to log the user onto the mail server. Calling the MAPISession1.Signon method forces the mail server to display the default logon screen for the e-mail system.
Listing 7.15. Coding the MAPIStart routine.
Public Sub MAPIStart()
'
' attempt to start a mapi session
'
On Error GoTo MAPIStartErr ' error trap
'
MAPISession1.SignOn ' start session
MAPIMessages1.SessionID = MAPISession1.SessionID ' pass ID
'
Exit Sub
'
MAPIStartErr:
MsgBox Error$, vbCritical, "Error " + Str(Err)
'
End Sub
Tip |
Notice the use of the error-handling routine. You'll see these throughout the application. Adding error handlers is always a good idea. Error handlers are even more critical whenever your programs are calling for system services like e-mail, since unexpected errors in the e-mail system can affect your Visual Basic program, too. |
Once your user has successfully logged onto the mail server, you need to check for any messages in the user's inbox. The MAPIFetch routine (see Listing 7.16) does this. The MAPIMessages1.Fetch method brings all messages from the inbox into the MAPI read buffer. You can then use a For...Next loop to "walk" through this buffer and read each message. This program pulls the messages into the read buffer and then copies the message header information (message subject, the sender's name, and the date and time the message was received) into a list box on the main form.
Listing 7.16. Coding the MAPIFetch routine.
Public Sub MAPIFetch()
'
' load all messages from 'inbox'
'
On Error GoTo MAPIFetchErr ' error trap
'
Dim x As Integer
Dim cLine As String
'
MAPIMessages1.Fetch ' get stuff from mail server
'
' now load into list box
'
List1.Clear
For x = 0 To MAPIMessages1.MsgCount - 1
MAPIMessages1.MsgIndex = x
cLine = MAPIMessages1.MsgSubject
cLine = cLine + Space(30)
cLine = Left(cLine, 30) + Space(2)
cLine = cLine + MAPIMessages1.MsgOrigDisplayName
cLine = cLine + Space(20)
cLine = Left(cLine, 52) + Space(2)
cLine = cLine + MAPIMessages1.MsgDateReceived
List1.AddItem cLine
Next x
'
Exit Sub
'
MAPIFetchErr:
MsgBox Error$, vbCritical, "Error " + Str(Err)
'
End Sub
The last support routine you need to add to the MAPIMAIN.FRM form is MAPISave (see Listing 7.17). This routine is used to save selected messages to your local workstation for later use. The common dialog box control is used to provide the standard save file dialog box. Once a valid name is given for the file, the routine writes out the message header information followed by the actual message text. This is saved as an ASCII file that can be loaded by Notepad or any standard text editor.
Listing 7.17. Coding the MAPISave routine.
Public Sub MAPISave()
'
' save the selected message as a text file
'
On Error GoTo MAPISaveErr ' error trap
'
' set dialog parms and show SaveAs box
'
CommonDialog1.Filter = "Text File|*.txt" ' file types to view/save
CommonDialog1.DialogTitle = "Save Mail Message" ' dialog caption
CommonDialog1.filename = "mailmsg.txt" ' suggest savename
CommonDialog1.Flags = &H2 ' force overwrite confirmation
CommonDialog1.ShowSave ' pop up the dialog
'
' if user picked a real name, save the message
'
If Len(CommonDialog1.filename) > 0 Then
Open CommonDialog1.filename For Output As 1
Print #1, "DATE:" + Chr(9) + MAPIMessages1.MsgDateReceived
Print #1, "FROM:" + Chr(9) + MAPIMessages1.MsgOrigDisplayName
Print #1, "TO:" + Chr(9) + MAPIMessages1.RecipDisplayName
Print #1, "SUBJ:" + Chr(9) + MAPIMessages1.MsgSubject
Print #1, "" ' blank line
Print #1, MAPIMessages1.MsgNoteText
Close #1
End If
'
Exit Sub
'
MAPISaveErr:
MsgBox Error$, vbCritical, "Error " + Str(Err)
'
End Sub
Now that you have coded the support routines, you need to add code for four Visual Basic events on the MAPIMAIN.FRM form.
The MAPIMAIN.FRM form has only five events that require code. Four of them are described here. The last event is described in the next section. The four events covered here are
The code for these events can be found in Listing 7.18.
Listing 7.18. Code for the Form and List1 events.
Private Sub Form_Load()
'
On Error GoTo FormLoadErr ' error trap
'
Me.Width = 9000 ' set starting width
Me.Height = 4500 ' set starting height
Me.Left = (Screen.Width - Me.Width) / 2
Me.Top = (Screen.Height - Me.Height) / 2
Me.Caption = "Simple Mail Client"
'
AdjustForm ' fix up display form
MAPIStart ' start MAPI Session
MAPIFetch ' get any new messages
'
Exit Sub
'
FormLoadErr:
MsgBox Error$, vbCritical, "Error " + Str(Err)
Unload Me
End Sub
Private Sub Form_Resize()
AdjustForm ' resize all controls as needed
End Sub
Private Sub Form_Unload(Cancel As Integer)
'
On Error Resume Next ' ignore error
MAPISession1.SignOff ' end mapi session
'
End Sub
Private Sub List1_DblClick()
'
' read the selected message
MAPIMessages1.MsgIndex = List1.ListIndex
MapiRead.Show vbModal
'
End Sub
The Form_Load event first sets the form size and location and then calls the support routines AdjustForm, MAPIStart, and MAPIFetch. If any of these routines returns an error, the program is halted. The Form_Resize event calls the AdjustForm routine. This automatically resizes all controls each time the user changes the size of the form during run-time. The Form_Unload event invokes the MAPISession1.SignOff method to end the e-mail session and log the user out of the message server. The List1_DblClick event gets the currently selected message and calls the MAPIREAD.FRM form to display the e-mail note. You'll code the MAPIREAD.FRM form later on.
The last code routine needed for the MAPIMAIN.FRM form is the code used for the Command1_Click event (see Listing 7.19). Since you built a command button array, all button clicks are sent to the same routine. The program will be able to tell which button was pressed by checking the Index parameter passed to the Click routine.
Listing 7.19. Coding the Command1_Click event.
Private Sub Command1_Click(Index As Integer)
'
' main command loop
'
On Error GoTo CommandErr ' error trap
'
Dim nTemp As Integer
'
Select Case Index
Case Is = 0
' open the selected message
If List1.ListIndex <> -1 Then
MAPIMessages1.MsgIndex = List1.ListIndex
MapiRead.Show vbModal
Else
MsgBox "No Message Selected", vbCritical, "Read Message"
End If
Case Is = 1
' start a new message
MAPIMessages1.Compose ' point to compose buffer
MAPIMessages1.Send True ' start new message dialog
Case Is = 2
' save the selected message
If List1.ListIndex <> -1 Then
MAPIMessages1.MsgIndex = List1.ListIndex
MAPISave
Else
MsgBox "No Message Selected", vbCritical, "Save Message"
End If
Case Is = 3
' delete the selected message
If List1.ListIndex <> -1 Then
nTemp = MsgBox("Delete Selected Message?", vbInformation + vbYesNo, &ACIRC;"Delete Message")
If nTemp = vbYes Then
MAPIMessages1.MsgIndex = List1.ListIndex
MAPIMessages1.Delete
MAPIFetch
End If
Else
MsgBox "No Message Selected", vbCritical, "Delete Message"
End If
Case Is = 4
' open the address book
MAPIMessages1.Show ' show address book
Case Is = 5
Listing 7.19. continued
' forward the selected message
If List1.ListIndex <> -1 Then
MAPIMessages1.MsgIndex = List1.ListIndex
MAPIMessages1.Forward
MAPIMessages1.Send True
Else
MsgBox "No Message Selected", vbCritical, "Forward Message"
End If
Case Is = 6
' reply to the originator of selected message
If List1.ListIndex <> -1 Then
MAPIMessages1.MsgIndex = List1.ListIndex
MAPIMessages1.Reply
MAPIMessages1.Send True
Else
MsgBox "No Message Selected", vbCritical, "Reply Message"
End If
Case Is = 7
' reply to all of selected message
If List1.ListIndex <> -1 Then
MAPIMessages1.MsgIndex = List1.ListIndex
MAPIMessages1.ReplyAll
MAPIMessages1.Send True
Else
MsgBox "No Message Selected", vbCritical, "Reply All Message"
End If
Case Is = 8
' check inbox for new messages
MAPIFetch ' call fetch routine
Case Is = 9
' exit program
nTemp = MsgBox("Exit Program?", vbInformation + vbYesNo, "Exit")
If nTemp = vbYes Then
Unload Me
End If
End Select
'
Exit Sub
'
CommandErr:
MsgBox Error$, vbCritical, "Error " + Str(Err)
'
End Sub
Each time a user presses one of the command buttons, this routine will execute the desired function. For most routines, the user must first select one of the messages in the inbox. If no message is selected, a dialog box pops up. Notice also that the only function that will require much code is the message-reading routine. You need to provide your own MAPI message reader (you'll use the MAPIREAD.FRM for that). All other e-mail services (New, Delete, Forward, Reply, ReplyAll, and AddressBook) are all provided by the message server your user logged onto at the start of the program.
Note |
There is, of course, a downside to this "easy-code" access to MAPI services. Simple MAPI does not allow you to read, write, or search the MAPI address book via code. You can only gain access to the address book by starting the address book dialog box with the MAPIMessages.Show method. Also, you cannot see any existing MAPI storage folders except the inbox. This means you cannot save messages to an existing folder, and you cannot read old messages stored in other folders in the past. These limitations make the Simple MAPI interface less than ideal for building robust MAPI clients. However, Simple MAPI is very good for general access to MAPI messages and for creating very simple e-mail interfaces. |
You need to code the MAPIREAD.FRM form to complete the project. This form has two support routines and four events that require code. The first support routine, AdjustReader, handles the resizing and locating of controls on the reader form. The second support routine, LoadReader, loads the message from the read buffer onto the form for display. This routine also creates a message header to display in the label control of the form. The code for these two support routines is shown in Listing 7.20.
Listing 7.20. Code for the MAPIREAD.FRM support routines.
Public Sub AdjustReader()
'
' arrange controls on the form
'
On Error Resume Next ' ignore any errors
'
' locate & size header label
Label1.Top = 120
Label1.Left = 120
Label1.Width = Me.Width - 360
Label1.Height = Me.Height * 0.3
'
' locate & size close button
cmdClose.Top = Me.Height - 840
cmdClose.Left = Me.Width - 1440
cmdClose.Width = 1200
cmdClose.Height = 300
'
' locate & size message text box
Text1.Top = Label1.Height + 240
Text1.Left = 120
Text1.Width = Me.Width - 360
Text1.Height = cmdClose.Top - (Text1.Top + 120)
'
End Sub
Listing 7.20. continued
Public Sub LoadReader()
'
' fill in message header and body
'
Label1.Caption = ""
Label1.Caption = "DATE: " + MapiMain.MAPIMessages1.MsgDateReceived + Chr(13)
Label1.Caption = Label1.Caption + "FROM: " + &ACIRC;MapiMain.MAPIMessages1.MsgOrigDisplayName + Chr(13)
Label1.Caption = Label1.Caption + "TO: " + &ACIRC;MapiMain.MAPIMessages1.RecipDisplayName + Chr(13)
Label1.Caption = Label1.Caption + "SUBJ: " + MapiMain.MAPIMessages1.MsgSubject
'
Text1.Text = MapiMain.MAPIMessages1.MsgNoteText
End Sub
The Form_Load event contains code to set the form size and then call the AdjustReader and LoadReader routines. The Form_Resize event calls the AdjustReader routine to resize the controls. The cmdClose_Click event unloads the MAPIREAD.FRM form, and the Text1_KeyPress event contains a single line of code that tells Visual Basic to ignore any key presses that occur within the text box control. This is a simple way to make a text box control read-only. Each time a user presses a key, the KeyPress event will zero out the ASCII key value before it gets typed to the screen. Listing 7.21 contains the code for the MAPIREAD.FRM form events.
Listing 7.21. Code for the MAPIREAD.FRM events.
Private Sub Form_Load()
'
Me.Width = 7500
Me.Height = 3750
Me.Left = (Screen.Width - Me.Width) / 2
Me.Top = (Screen.Height - Me.Height) / 2
Me.Caption = "Read Mail [" + MapiMain.MAPIMessages1.MsgSubject + "]"
'
AdjustReader ' arrange controls on form
LoadReader ' fill in header and body
'
End Sub
Private Sub Form_Resize()
AdjustReader ' arrange controls on form
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = 0 ' ignore all key presses
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
After you add all the code, save the project (MAPICLN.VBP) and run it. When the program first starts, you'll see a prompt to log onto your e-mail server. After you log on, you'll see the main form of the application (see Figure 7.7).
Figure 7.7 : The main form of the simple e-mail client.
This form shows all the e-mail messages that are currently in your inbox. Notice that you can resize the form, and all the controls will adjust to the new form dimensions. If you double-click an item in the list box or select an item with a single click and press the Read button, you'll see the MAPIREAD.FRM form with the message header and selected e-mail message (see Figure 7.8).
Figure 7.8 : Displaying the message reader form.
If you press the New button, you'll see the default message compose dialog box. This box will look different depending on the e-mail system you are using. Figure 7.9 shows how the Microsoft Exchange compose dialog box looks in Windows 95.
Figure 7.9 : The Microsoft Exchange compose dialog box.
You can get direct access to the e-mail address book by clicking the Addr command button on the MAPIMAIN.FRM form. Figure 7.10 shows what the Microsoft Exchange address book looks like in Windows 95.
Figure 7.10 : The Microsoft Exchange address book.
You can test the application by sending yourself e-mail and then using the various command buttons to forward, reply, save, and delete e-mail messages. You now have a completed e-mail client application!
Even though this project is fairly complete, there are a few features you might consider adding to improve the program. Some possible enhancements are
This chapter covered two main topics:
You learned the properties and methods of the two Visual Basic MAPI controls. The MAPISession control is used to gain access to MAPI service providers through the SignOn and SignOff methods. The MAPIMessages control is used to read, create, delete, address, and send MAPI messages.
The Simple MAPI client detailed in this chapter showed you how to build a complete MAPI-enabled application with a minimum of coding. This sample application shows how you can use the Visual Basic MAPI controls to create a fully functional e-mail client that can read and delete incoming messages, compose new messages, address them, and send them to their recipients.
You also learned that Simple MAPI services allow only limited access to the MAPI address book. You can search and edit the address book only through the pre-defined MAPI.Show method. You cannot directly search for existing addresses or add, edit, or delete addresses without using the address dialog box supplied by the MAPI service provider.
You also learned that Simple MAPI does not allow you to access any of the existing mail folders. You can only see the inbox folder and its contents.
Now that you know how to use the Visual Basic MAPI controls to create a simple e-mail client, you're ready to tackle OLE messaging. In the next chapter, you'll learn how to build a mailing list server application that is capable of managing large mailing lists.