Electronic mail capabilities are fast becoming a "must-have" feature for desktop applications. Most network installations today have at least one mail server. Some offices even have multiple mail and messaging platforms all running on the same
network. Design specifications for custom applications often includes the capability to send program output to other locations via electronic transfer as one of the basic requirements of the system.
In this chapter, you'll learn how to use the Microsoft Mail Application Programmer Interface (MAPI) to add electronic mail capabilities to your Visual Basic applications. First, you'll get a quick overview of the MAPI interface itself. Then you'll
review the two Visual Basic controls you can use to create MAPI applications with Visual Basic. Finally, you'll work through programming examples of the three most common MAPI applications: electronic mail (e-mail) applications, mail-aware applications,
and mail-enabled applications.
When you complete this chapter, you'll have a good understanding of the Microsoft MAPI interface and the Visual Basic MAPI controls. You will also be able to design and build applications that can use the MAPI interface to provide mail services from
within your Visual Basic programs.
The Mail Application Programming Interface (MAPI) is a set of API calls that has become the de facto standard for creating e-mail-capable applications for the Windows environment. The MAPI standards provide a high-level set of tools for linking any
Windows application with electronic mail message services. You can use these tools to create client applications that can compose, send, and receive electronic messages with any other valid address recognized by the mail server.
The real advantage of using MAPI is that most of the mail servers on the market today recognize and comply with the MAPI standard. If you write your program using MAPI, it will work with Microsoft Mail and Microsoft Exchange without any programming
changes at all. You can also expect it to work with non-Microsoft products like Novell's Group Wise, Lotus cc:Mail, and any other e-mail system that is MAPI compatible.
There are two major components to any messaging system: the server component and the client component. In typical network installations, the mail server usually operates from a single workstation somewhere on the network. One or more client applications
can run on the individual workstations connected to the network. The mail server handles all messaging requests generated by the mail client application. MAPI acts as a translator between your Visual Basic client program and the mail server that processes
all electronic messages. This chapter deals with the client side of electronic mail applications.
Because MAPI is a high-level set of standards, there are really only a handful of basic operations to learn before you can start designing and building mail-aware applications. Along with a core set of functions, there are several support functions you
can use to increase the feature set of your Visual Basic mail applications. You'll learn about the core services and the support routines later in this chapter. But first, take a look at the different types of MAPI applications that exist today.
The topic of mail applications includes a wide range of applications. Any program that can interact with the underlying mail services can be thought of as a mail application. This can range from simple programs that allow users to send and receive
one-line messages on up to major systems that are capable of automatically transferring large amounts of data to any location in the world. For the purposes of this chapter, mail applications can be divided into three main groups:
Even though all these programs provide some level of interaction with the available mail services, they each have their own set of features that set them apart.
E-mail programs are applications that act as a front-end to the mail server. These applications allow users to create, read, and send messages to each other. Usually, e-mail programs also allow users to define and maintain a list of commonly used e-mail
addresses. While all e-mail programs allow users to compose and send text messages, most also provide features for sending binary files such as graphic images, spreadsheets, and so on. These nontext portions of the message are called attachments.
Mail-aware applications are programs that provide electronic send and/or receive services as a part of their basic feature set. Mail-aware software is able to use the available mail services much in the same way programs use available printers, modems,
or storage media (disk drives, CD-ROMs, and so on). For example, most office suite applications (word processing, spreadsheet, and so on) provide a "Send" feature on the main menu of all their programs. Basically, whatever documents you can
create with the program can be sent to other locations using the mail services available on the network.
The third class of applications goes even further in providing mail services as part of their basic structure. These applications are usually referred to as mail-enabled applications. These applications use mail services to perform all or part of their
primary task. Even more important, users may not even know they are using the mail services. The use of mail services is embedded in the very design of the application. A good example of a mail-enabled application is a trouble call program that prompts
users to enter details about a customer service complaint and then automatically forwards the information to one or more individuals who can then act on the request. The person entering the data may not be aware that the information is forwarded on to
others using the same network services that are used to send company e-mail messages.
The MAPI standards define a small set of core routines for providing mail services to client applications. The core services can be divided into two groups:
In a typical MAPI session, you need to first establish a connection to the mail server. This involves providing a valid user address and password for the mail server that you are attempting to communicate with. If the user name and password are valid
for this mail server, MAPI will return a unique session ID number that will be used in all communications between your Visual Basic program and the mail server.
Once the MAPI session is established, your program has access to the message services provided by the mail server. The core services provided by MAPI-compliant systems include:
This list of message services is provided to the client application by the mail server. In other words, the client application tells the server that the client wants to compose a new message. The server then provides all the functionality needed to
compose the message. When the client asks for a list of valid addresses, the server provides the list and lets the client select one or more names as the destination address for the message. Finally, when the client tells the server to deliver the message,
the server takes the address list and forwards the composed message to each address in the destination list.
The key concept to keep in mind here is that the mail server is performing all the tasks—not the client program. You can write a simple electronic mail program by sending a handful of service requests to the mail server. In fact, later in this
chapter, you learn how to create a ten-line Visual Basic program that can compose and send an e-mail message to any valid address.
You can also gain access to MAPI functions that allow your Visual Basic program to provide replacements for many of the high-level MAPI services. You can create your own message input screen, then supply the completed message to the mail server for
addressing and delivery. You could also provide your own addressing services and simply tell the mail server to forward the completed and fully addressed message to the appropriate location.
To sum up, no matter how much your Visual Basic program requests of the mail server, the same set of functions must always occur when dealing with the MAPI interface. All MAPI sessions involve the following set of operations:
The rest of this chapter will show you how you can use the MAPI controls that ship with Visual Basic 4.0 Professional Edition to perform the preceding tasks. You will also learn how to use the MAPI controls to create the three types of mail applications
(e-mail, mail-aware, and mail-enabled).
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 MAPI Session control provides access to everything
you'll need to sign on and sign off any MAPI-compliant server. The MAPI Message control provides access to the MAPI routines that allow you to read, compose, address, and send messages using the session established with the MAPI Session control. This
section of the chapter will review the MAPI-related properties and methods of each of these controls.
The MAPI Session 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 (Windows 95 only) 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 MAPI Session control that are directly MAPI related. The following two sections identify these components of the MAPI Session control, their meaning, and their use in Visual Basic programs.
There are only two MAPI Session methods: SignOn and SignOff. The SignOn method is used to begin a MAPI session. By default, the SignOn method provides a log-in dialog box that prompts the user for valid log-in information. The exact nature of the log-in
dialog box depends on the mail server. The Microsoft Mail log-in dialog box prompts the user for a valid username and password (see Figure 25.1).
Figure 25.1. Default log-in dialog box for Microsoft Mail.
The default log-in dialog box for the Microsoft Exchange Mail product simply asks the user to select the desired mail services profile (see Figure 25.2).
Figure 25.2. Default log-in dialog box for Microsoft Exchange Mail.
If a valid username and password are supplied via the SignOn method, the MAPI Session control returns a unique value in the SeesionID property. This unique value is used in all message transactions to identify the link between the client application and
the mail server. You'll learn more about the SessionID property in the next section.
The SignOff method of the MAPI Session control does just what you'd expect. You use the SignOff method to safely end your link to the mail server. There is no dialog box associated with the SignOff method.
In order to use the MAPI Session control methods, you must first place the MAPI Session control on a Visual Basic form. The form is invisible at run-time and is used only 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 MAPI Session control, start a Visual Basic project. Use the Tools | Custom Controls menu item to add the Microsoft MAPI controls to your project. Place a MAPI Session control on the form and add the following code to the form
load event.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.SignOn MAPISession1.SignOff End ' End Sub
Save the form as vbu2501.frm and the project as vbu2501.vbp and run the project. You'll see the default log-in dialog box provided by your mail server. After you sign in, the Visual Basic program immediately signs you out and ends. You'll add more
features as you go along.
The MAPI Session control has seven MAPI-related properties. These properties all deal with options that you can set to control the behavior of the control at log-in 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 log-in time. By default, all new messages are forced to the user's mail box at log-in time. You can set this property to False to prevent this from
happening. In the following code example, the DownloadMail property has been set to False before invoking the SignOn method.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.DownloadMail = False ' dont get new mail MAPISession1.SignOn MAPISession1.SignOff End ' End Sub
The LogonUI property can be used to turn off the default log-in screen provided by the mail server. You can set this property to False to suppress the mail server from presenting the log-in 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 session before attempting to log
into 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. Listing 25.3 shows how you can accomplish this.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.DownloadMail = False ' dont get new mail MAPISession1.NewSession = True ' force a unique 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 log-in screen. If you supply a UserName but leave the Password property blank, the SignOn method will force the log-in dialog box to appear to fill out
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 log-in dialog box.
Listing 25.4 shows how to perform an automatic log-on for Microsoft Mail. If you want to log on to Microsoft Exchange, replace the UserName with a valid Exchange profile name (MS Exchange Settings is the default) and leave the Password property blank.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.DownloadMail = False ' dont get new mail MAPISession1.NewSession = True ' force a unique 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. This value is used to set the SessionID of the MAPI Message control before attempting to access the message services provided by the mail server.
In Listing 25.4, you'll see an added message box that shows the unique MAPI Session Handle.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.DownloadMail = False ' don't get new mail MAPISession1.NewSession = True ' force a unique session MAPISession1.UserName = "VBU Profile" ' username for mail MAPISession1.Password = "" ' users 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 log-in 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 link (see Figure 25.3).
Figure 25.3. Displaying the SessionID of a MAPI Link.
The MAPI Message 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 MAPI Message control provides services for reading, composing,
addressing, and sending mail messages. You can perform all major mail operations simply by requesting the service from the server.
The MAPI Message control has four primary responsibilities:
There are 11 methods and over 30 properties of the MAPI Message control that are MAPI-related. These methods and properties are reviewed briefly here. You can find additional documentation on each of the MAPI Message properties in the Visual Basic
online help files.
There are 11 methods for the MAPI Message control. These methods fall into four general categories:
The message creation methods account for six of the 11 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 will attempt to send the new message to the address supplied. If an address or message is not supplied, the Send method will force 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 you started earlier in this chapter. The following code in Listing 25.6 is all you need to be able to create a Visual Basic application that can compose and
send e-mail messages. Start a new Visual Basic project and add the MAPI Session and the MAPI Message controls to the form. Then add the following code to the Form_Load event.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.SignOn ' log into MAPI server MAPIMessages1.SessionID = MAPISession1.SessionID ' MAPIMessages1.Compose ' clear buffers MAPIMessages1.Send True ' show default form ' MAPISession1.SignOff ' exit MAPI server End ' End Sub
Now save the form as vbu2502.frm and the project as vbu2502.vbp and run the program. You'll be prompted for a log-in, and then you'll see the default compose form. Figure 25.4 shows what comes up if you are using Microsoft Exchange Mail.
Figure 25.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. You'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 and ReplyAll methods place RE: at the start of the subject line.
The code in Listing 25.7 takes the first message in the user's Inbox and copies it to the compose buffer with FW: on the subject line.
Private Sub Form_Load() ' ' smallest e-mail program ' MAPISession1.SignOn ' log into MAPI server MAPIMessages1.SessionID = MAPISession1.SessionID ' MAPIMessages1.Fetch ' get meesages 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-in user. The following code example fetches all the messages for the user and then uses the
MsgCount property to find out how many messages are actually on file.
Private Sub Form_Load() ' ' smallest e-mail program ' 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 following
code in Listing 25.9 removes the current message from the user's collection.
Private Sub Form_Load() ' ' smallest e-mail program ' 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. You can also use the Show method to display details of the current message recipient (if this is supported by the MAPI mail
server). The following code in Listing 25.10 will display the current mail server address list.
Private Sub Form_Load() ' ' smallest e-mail program ' 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 MAPI Message control has more than 30 MAPI-related properties. I will go through a quick review of them here. You can find more detailed information on each of the MAPI Message control properties by consulting the topic "MAPI Message
Control" in the Visual Basic on-line help file.
The MAPI Message 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 25.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 the user to modify the contents of the address book. Default is False. |
|
AddressResolveUI |
When set to True, presents a dialog box to help the user resolve rejected addresses. Use this property in conjunction with the ResolveName method. Default is False. |
Attachment |
AttachmentCount |
Contains the number of attachments for the current message. |
|
AttachmentIndex |
Pointer to the current attachment in the list. |
|
AttachmentName |
File name of the attachment pointed to by the AttachmentIndex property. |
|
AttachmentPathName |
Contains full path name 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. 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. 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 which 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 code is left null or empty to indicate an Interpersonal Message (IPM). |
Recipient |
RecipAddress |
Address of the current recipient (could be a list of 'em!). |
|
RecipCount |
Contains the number of recipients for the current piece of mail. |
|
RecipDisplayName |
The "display name" associated with 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 RecipType flag. OrigList = 0 (the message editor); 1 = a (person in the TO: address list; 2 = a (person on the Carbon Copy list); 3 = a (person on the BccList/blind Carbon Copy list). |
Other |
Action |
Carry-over from Visual Basic 3.0—use the new methods instead. |
|
SessionID |
Contains the value of the SessionID generated by the MAPI Session 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 carbon copy recipients, and so on.
There are a number of things you can do with the numerous properties of the MAPI Message control, but one of the most useful is the capability 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 MAPI Message control and Visual Basic 4.0. Attachments can be simple text files, word processing documents, and even databases. For this example, you'll attach a system file from a
user's work station 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. These four properties are:
You can add an attachment to any valid message in the compose buffer. The following code example creates a new message and adds the workstation's CONFIG.SYS file as an attachment. Modify the FormLoad event of vbu2502.frm to match the code in Listing
25.11.
Private Sub Form_Load() ' ' smallest e-mail program ' 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 vbu2502.vbp project. After logging into the mail server, you'll see a form appear with the C:\CONFIG.SYS file already attached to the message (see Figure 25.5).
Figure 25.5. Viewing an added attachment to the message.
In the final three sections of this chapter, you will create three different MAPI applications using Visual Basic 4.0. Each application will illustrate the three types of mail applications:
In this first programming example, you'll build a very simple electronic mail application that will get any new messages sent to the user and will allow the user to edit, store, and/or delete those messages. The user will also be able to create and
maintain addresses in their personal address book.
This application will require very little in the way of Visual Basic code and only two forms are needed. The first form will be the main form that the user sees. This form will contain a list of all the messages in the user's Inbox and a set of buttons
giving the user access to the various message services. Refer to Figure 25.6 and Table 25.2 for layout details.
Figure 25.6. Laying out the main form for the Simple Mail Tool.
Control |
Property |
Setting |
Form |
Name |
Main |
|
Caption |
Simple Mail Tool |
|
Height |
4440 |
|
Left |
1380 |
|
Top |
1710 |
|
Width |
6555 |
Command Button |
Name |
Command1(0) |
|
Caption |
&New |
|
Height |
300 |
|
Left |
5100 |
|
Top |
120 |
|
Width |
1200 |
Command Button |
Name |
Command1(1) |
|
Caption |
&Copy |
|
Height |
300 |
|
Left |
5100 |
|
Top |
540 |
|
Width |
1200 |
Command Button |
Name |
Command1(2) |
|
Caption |
&Forward |
|
Height |
300 |
|
Left |
5100 |
|
Top |
960 |
|
Width |
1200 |
Command Button |
Name |
Command1(3) |
|
Caption |
R&eply |
|
Height |
300 |
|
Left |
5100 |
|
Top |
1380 |
|
Width |
1200 |
Command Button |
Name |
Command1(4) |
|
Caption |
Reply &All |
|
Height |
300 |
|
Left |
5100 |
|
Top |
1800 |
|
Width |
120 |
Command Button |
Name |
Command1(5) |
|
Caption |
&Delete |
|
Height |
300 |
|
Left |
5100 |
|
Top |
2220 |
|
Width |
1200 |
Command Button |
Name |
Command1(6) |
|
Caption |
&Read |
|
Height |
300 |
|
Left |
5100 |
|
Top |
2640 |
|
Width |
1200 |
Command Button |
Name |
Command1(7) |
|
Caption |
Address &Book |
|
Height |
300 |
|
Left |
5100 |
|
Top |
3060 |
|
Width |
1200 |
Command Button |
Name |
Command1(8) |
|
Caption |
E&xit |
|
Height |
300 |
|
Left |
5100 |
|
Top |
3600 |
|
Width |
1200 |
List Box |
Name |
List1 |
|
Height |
2790 |
|
Left |
120 |
|
Top |
480 |
|
Width |
4815 |
Label |
Name |
Label1 |
|
BorderStyle |
1 - Fixed |
|
Caption |
Messages: |
|
Height |
255 |
|
Left |
120 |
|
Top |
120 |
|
Width |
4815 |
MAPI Session |
Name |
MAPISession1 |
MAPI Message |
Name |
MAPIMessages1 |
Now you can add the code behind the controls. First add the code that will perform the MAPI Session log-on. Place the code in Listing 25.12 in the FormLoad event of the form.
Private Sub Form_Load() ' ' attempt signon ' On Error GoTo FormLoadErr ' MAPISession1.SignOn ' tell server to log me in MAPIMessages1.SessionID = MAPISession1.SessionID GetMessages ' get lots of messages ' Exit Sub ' FormLoadErr: MsgBox Error$, vbCritical, "Error Code " + Str(Err) Unload Me End End Sub
This routine calls a module to get the messages (GetMessage). I'll define that in just a bit. Next, add the code in Listing 25.13 to the Form_Unload event.
Private Sub Form_Unload(Cancel As Integer) ' On Error Resume Next MAPISession1.SignOff ' End Sub
Now it's time to create a new Sub procedure called GetMessages. The routine in Listing 25.14 will fetch the messages from the mail server and load the subject lines into the list control for you to view.
Public Sub GetMessages() ' ' get all unread stuff from this user ' Dim x As Integer Dim cLine As String ' On Error GoTo GetMessagesErr ' MAPIMessages1.Fetch ' get messages from server ' List1.Clear ' clear local list control If MAPIMessages1.MsgCount > 0 Then ' got at least one? For x = 0 To MAPIMessages1.MsgCount - 1 MAPIMessages1.MsgIndex = x ' move pointer cLine = MAPIMessages1.MsgSubject ' get subject List1.AddItem cLine ' add to list control Next x End If ' Exit Sub ' GetMessagesErr: MsgBox Error$, vbCritical, "Error Code: " + Str(Err) Unload Me ' End Sub
The next routine you need is the one that responds to the command button array. Because you built the control array, you can place all the real substantial commands in one module. Place the code in Listing 25.15 in the Command1_Click event.
Private Sub Command1_Click(Index As Integer) ' ' handle user clicks ' On Error GoTo Command1ClickErr ' Dim nTemp As Integer ' Select Case Index Case 0 ' new message MAPIMessages1.Compose ' clear compose buffer MAPIMessages1.Send True ' start server dialog Case 1 ' copy message MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg MAPIMessages1.Copy ' copy in to compose buffer MAPIMessages1.Send True ' start server dialog Case 2 ' forward message MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg MAPIMessages1.Forward ' copy as forwarded in to buffer MAPIMessages1.Send True ' start dialog Case 3 ' reply to message MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg MAPIMessages1.Reply ' copy as reply into buffer MAPIMessages1.Send True ' start server dialog Case 4 ' reply to all senders MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg MAPIMessages1.ReplyAll ' copy as reply all into buffer MAPIMessages1.Send True ' start server dialog Case 5 ' delete message nTemp = MsgBox("Delete Current Message?", vbYesNo, "Delete Message") If nTemp = vbYes Then ' if confirmed delete MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg MAPIMessages1.Delete ' tell server to delete msg GetMessages ' refresh local list End If Case 6 ' read message MAPIMessages1.MsgIndex = List1.ListIndex ' point to msg Reader.Show vbModal ' start read form Case 7 ' address book MAPIMessages1.Show ' show book Case 8 ' exit program nTemp = MsgBox("Exit Program?", vbInformation + vbYesNo, "Program _Exit") If nTemp = vbYes Then ' if confirmed exit Unload Me ' shut down End If End Select ' Exit Sub ' Command1ClickErr: MsgBox Error$, vbCritical, "Error Code: " + Str(Err) ' End Sub
The only thing you have left to do here is to add a line of code to the List1_DblClick event. The line of code in Listing 25.16 will fire off the Click event for the Read button each time the user double-clicks on an item in the list.
Private Sub List1_DblClick() Command1_Click 6 ' read message End Sub
Save this form as vbu2503.frm and the project as vbu2503.vbp. You can run this if you wish. You can perform all the tasks except reading existing messages. You'll add that form next.
Add a new form to the project. Use Figure 25.7 and Table 25.3 to complete the form layout.
Figure 25.7. Laying out the reader form.
Control |
Property |
Setting |
Form |
Name |
Reader |
|
Caption |
Read Message |
|
Height |
5310 |
|
Left |
1080 |
|
Top |
1170 |
|
Width |
6810 |
Label |
Name |
Label1 |
|
BorderStyle |
1 - Fixed |
|
Font |
MS LineDraw, 10pt |
|
Height |
1035 |
|
Left |
120 |
|
Top |
180 |
|
Width |
6435 |
Text Box |
Name |
Text1 |
|
Height |
3075 |
|
Left |
120 |
|
MultiLine |
-1 True |
Text Box |
ScrollBars |
2 - Vertical |
|
Top |
1200 |
|
Width |
6435 |
Command Button |
Name |
Command1 |
|
Caption |
&Close |
|
Height |
300 |
|
Left |
5340 |
|
Top |
4440 |
|
Width |
1200 |
You need only three code pieces for this form. The first occurs in the Form_Load event. The code in Listing 25.17 loads the label and the text controls.
Private Sub Form_Load() ' ' load message into form ' On Error GoTo FormLoadErr ' Label1 = "Date: " + Main.MAPIMessages1.MsgDateReceived + Chr(13) Label1 = Label1 + "From: " + Main.MAPIMessages1.MsgOrigDisplayName + _Chr(13) Label1 = Label1 + "Subject: " + Main.MAPIMessages1.MsgSubject + Chr(13) ' Text1 = Main.MAPIMessages1.MsgNoteText ' Exit Sub ' FormLoadErr: MsgBox Error$, vbCritical, "Error Code: " + Str(Err) Unload Me End Sub
The only other things you'll need are a line behind the Exit button and a line to disable data entry in the text control. First, add to code in Listing 25.18 behind the Exit button.
Private Sub Command1_Click() Unload Me End Sub
Now add the following line of code in Listing 25.19 to the KeyPress event of the Text box control. This code will ignore any attempts to type within the control.
Private Sub Text1_KeyPress(KeyAscii As Integer) KeyAscii = 0 ' ignore all keys End Sub
Save this form as vbu2503b.frm and run the project. After responding to the MAPI Log-In dialog box, you'll see the main form (see Figure 25.8).
Figure 25.8. Running the Simple Mail Tool.
You now have a fully functional mail front end with less than 100 lines of code! Of course, you could spice this up with other features and goodies, too.
The next category of MAPI applications is the mail-aware application. This is a program that offers mail services as an "added feature." A good example of this is the Send option in Word, Excel, Access, and the other Microsoft Office programs.
Making your Visual Basic programs "mail-aware" is about the same as making them aware of a printer. Usually, you can add a Send option to the main menu and treat the output to the mail server the same way you produce output to the printer. It
is possible that you may have to create an interim ASCII text file that you can then import into the message text using the clipboard or a few lines of Visual Basic code. All in all, it's quite easy.
For this example, you'll borrow the code from a sample program that ships with Visual Basic 4.0 Standard Edition: the MDI sample application. This can be found in the samples\mdi\ folder within the main Visual Basic folder. If you do not have this
application or if you want to leave your copy alone, you can find another copy of it in the \vbu\chap25\mdi folder on the CD-ROM shipped with this book.
This MDI application is a simple project that creates a multi-document editor that can save documents as ASCII files. To make this system mail-aware will require a few lines of code behind a Send... menu item in one form.
Load the MDI project and open the NOTEPAD form. First, add the MAPI Session and MAPI Message controls to the bottom of the form. Next, add a separator line and a Send... menu item just after the Save As... menu item (see Figure 25.9).
Figure 25.9. Modifying the NOTEPAD form.
Finally, add the code in Listing 25.20 to the mnuFileSend_Click event. This is all the code you need to make this application mail-aware.
Private Sub mnuFileSend_Click() ' ' log onto mail server ' start mail compose session ' log off mail server ' On Error GoTo mnuFileSendErr ' ' MAPISession1.DownloadMail = False ' dont check box MAPISession1.SignOn ' start mail session MAPIMessages1.SessionID = MAPISession1.SessionID ' ' handle sending msg MAPIMessages1.Compose ' clear buffer MAPIMessages1.MsgNoteText=Me.Text1 ' move text to message MAPIMessages1.MsgSubject = Me.Caption ' get subject MAPIMessages1.Send True ' show server dialog ' MAPISession1.SignOff ' end mail session ' Exit Sub ' mnuFileSendErr: MsgBox Error$, vbCritical, "Mail Send Error " + Str(Err) On Error Resume Next MAPISession1.SignOff ' End Sub
Notice that the DownloadMail property is set to skip over checking the Inbox. The Inbox isn't important here; you just want to send this document to someone via the mail server. The message text and message subject are set using data from the input
form.
Now save and run the project. Begin to edit a new document (see Figure 25.10).
Figure 25.10. Using the MDI application.
When you are done editing the text, select the Send... menu item to send the document out. You'll see the default compose form appear with the text and subject already supplied (see Figure 25.11).
Figure 25.11. The MDI text ready to address and send.
There is a way to "bury" the mail features even deeper into this application. You really only need a way to tack on an address to this document. The following code shows a modified routine that calls only the address dialog and then sends the
document out.
Private Sub mnuFileSend_Click() ' ' log onto mail server ' start mail compose session ' log off mail server ' On Error GoTo mnuFileSendErr ' ' MAPISession1.DownloadMail = False ' dont check box MAPISession1.SignOn ' start mail session MAPIMessages1.SessionID = MAPISession1.SessionID ' ' handle sending msg MAPIMessages1.Compose ' clear buffer MAPIMessages1.MsgNoteText = Me.Text1 ' get text MAPIMessages1.MsgSubject = Me.Caption ' get subject MAPIMessages1.Show ' get address MAPIMessages1.Send ' send without dialog ' MAPISession1.SignOff ' end mail session ' Exit Sub ' mnuFileSendErr: MsgBox Error$, vbCritical, "Mail Send Error " + Str(Err) On Error Resume Next MAPISession1.SignOff ' End Sub
Save and run this project. When you select the Send... menu, you now will see only the address dialog before the program sends your document out to the server.
As you can see, it's not at all difficult to add mail features to your existing applications.
The final category of mail applications to demonstrate is the "mail-enabled" type. This is a program that has mail services as a basic part of its structure. In this case, you will build a single form that will handle trouble call reports and
route the message to an appropriate person for resolution. This is a very simplistic version of a mail-aware application, but it will touch on the main points.
Use Figure 25.12 and Table 25.4 to lay out the simple trouble call data entry form.
Figure 25.12. Laying out the mail enabled Trouble Call form.
Controls |
Property |
Setting |
Form |
Name |
frmTrouble |
|
Caption |
Trouble Call Report |
|
Height |
3690 |
|
Left |
1035 |
|
Top |
1155 |
|
Width |
5640 |
Label |
Name |
Label1 |
|
Borderstyle |
1 - Fixed |
|
Caption |
Customer: |
|
Height |
300 |
|
Left |
120 |
|
Top |
120 |
|
Width |
1200 |
Label |
Name |
Label2 |
|
Borderstyle |
1 - Fixed |
|
Caption |
Problem: |
|
Height |
300 |
|
Left |
120 |
|
Top |
540 |
|
Width |
1200 |
Text Box |
Name |
Text1 |
|
Height |
300 |
|
Left |
1440 |
|
Top |
120 |
|
Width |
3915 |
Text Box |
Name |
Text2 |
|
Height |
2115 |
|
Left |
1440 |
|
Multi-Line |
True |
|
ScrollBars |
2 - Vertical |
|
Top |
540 |
|
Width |
3915 |
Command Button |
Name |
Command1(0) |
|
Caption |
&Send |
|
Height |
300 |
|
Left |
1440 |
|
Top |
2820 |
|
Width |
1200 |
Command Button |
Name |
Command1(1) |
|
Caption |
&Cancel |
|
Height |
300 |
|
Left |
2820 |
|
Top |
2820 |
|
Width |
1200 |
Command Button |
Name |
Command1(2) |
|
Caption |
E&xit |
|
Height |
300 |
|
Left |
4200 |
|
Top |
2820 |
|
Width |
1200 |
MAPI Session |
Name |
MAPISession1 |
MAPI Message |
Name |
MAPIMessages1 |
This time, you'll write four standalone routines that you can call from the main form control events. First, create a new Sub procedure called DOMAPILogOn and add the code in Listing 25.22.
Public Sub DoMAPILogOn() ' ' attempt to log on to mail services ' On Error GoTo DoMAPILogOnErr ' MAPISession1.DownloadMail = False MAPISession1.UserName = "MS-Mail Only" MAPISession1.SignOn MAPIMessages1.SessionID = MAPISession1.SessionID Exit Sub ' DoMAPILogOnErr: MsgBox Error$, vbCritical, "Error Code: " + Str(Err) + " [DoMAPILogOn]" Unload Me End End Sub
Notice that we are supplying a predefined user name in this routine. As long as this is a valid login name, Microsoft Exchange will automatically log the user in without any dialog box appearing. This value could be stored in an INI/Registry setting or
in a database. The key here is that you are establishing the link to messaging services without asking for input from the user.
Now create a new Sub procedure called DoMAPILogOff and enter the code in Listing 25.23.
Public Sub DoMAPILogOff() ' ' log off mapi services ' On Error Resume Next MAPISession1.SignOff ' End Sub
Nothing special here. It's just the standard log out of the messaging server. The next routine is the one that sends the message without bothering the user again. Create a Sub procedure called DoMAPISend and add the code in Listing 25.24.
Public Sub DoMAPISend() ' ' put together message and ' ship it out ' On Error GoTo DoMAPISendErr ' MAPIMessages1.Compose MAPIMessages1.MsgSubject = "Trouble Report for " + Me.Text1 MAPIMessages1.MsgNoteText = Me.Text2 MAPIMessages1.RecipAddress = "MS:COMTRAX/PO1/mca" MAPIMessages1.Send ' Exit Sub ' DoMAPISendErr: MsgBox Error$, vbCritical, "Error Code: " + Str(Err) + " [DoMAPISend]" Exit Sub End Sub
Here, we clear the compose buffer, work up the subject line, load the text, and then address it ourselves. The recipient address can be stored in the program, in INI/Registry settings, or in a database. More sophisticated programs would allow
configuration routines to modify this parameter as needed—maybe even send the message to different (or multiple) people, depending on the type and severity of the trouble call. All this logic can be kept in your Visual Basic application and used to
perform messaging services without requiring the user to know anything about e-mail or electronic messaging.
Add this final Sub procedure in Listing 25.25 to clear out the input fields for data entry.
Public Sub ClearForm() ' ' clear this form for next input ' Text1 = "" Text2 = "" End Sub
Now that the core routines are done, you need to place some code at the key events in the form. Listing 25.26 contains the code pieces for the Form_Load and Form_Unload events.
Private Sub Form_Load() DoMAPILogOn ClearForm End Sub Private Sub Form_Unload(Cancel As Integer) DoMAPILogOff End Sub
Finally, add the Select Case structure to handle the command buttons as in Listing 25.27.
Private Sub Command1_Click(Index As Integer) ' ' handle user clicks ' Select Case Index Case 0 ' send out report DoMAPISend ClearForm Case 1 ' cancel this report ClearForm Case 2 ' exit this program Unload Me End Select ' End Sub
Save this form as vbu2504.frm and the project as vbu2504.vbp. Now run the program. Assuming you have added valid login and recipient address data, your program will log itself in without prompts and then show the data entry form (see Figure 25.13).
Figure 25.13. Running the mail-enabled Trouble Call Report.
When you press the Send key, the data will be packaged up and sent to the predetermined e-mail location.
As mentioned earlier, this is a very simple mail-enabled application. There is no limit to the types of applications you can develop using the MAPI controls to provide messaging services for your Visual Basic programs.
This chapter covered several general issues concerning the MAPI message standard. The key points are:
You learned that there are two Visual Basic MAPI controls. The MAPI Session control provides user log-in and log-out services for linking the Visual Basic client application with the mail server. The MAPI Message control provides all other
message services including reading, composing, addressing, and sending electronic messages and attachments.
Lastly, you learned how to use the Visual Basic MAPI controls to build three sample applications. These applications illustrated the differences between the three main categories of messaging programs: e-mail, mail-aware, and mail-enabled.