How to Send and Receive Mail Using Visual Basic 4.0

by Dave Grundgeiger



Like other useful computer tools, electronic mail benefits from automation. Would you like to write a utility that monitors a file server’s resources and sends you an email when resources are low? You can do that with Visual Basic and Microsoft's Messaging Application Programming Interface (MAPI). Or would you like to write a help desk call log program that emails a technician when a new call is entered into the database? You can do that too. In this article I'll show you the basics of sending and receiving electronic mail.

The Tools You'll Need

I'm using Visual Basic 4.0 for 32-bit development, running under Windows 95. This version of VB includes the two controls that will be at the center of every mail-enabled application you write: the MAPI session control and the MAPI messages control. The MAPI session control is used to establish and control a Microsoft Mail session, and the MAPI messages control is used to create and work with mail messages. You can also use the 16-bit Visual Basic 4.0 platform.

You'll also need to be running a MAPI-compliant messaging system. I'm using Microsoft Exchange, but Windows for Workgroups, Microsoft Mail or Outlook should work just as well. Make sure that the messaging system is running correctly (i.e. check that you can send and receive emails) before proceeding.

Getting Started

You'll need to add the MAPI controls to your Visual Basic toolbox each time you start a new mail-enabled project. To do so, from the Visual Basic menu bar, select Tools, then Custom Controls. The Custom Controls dialog box appears as shown in Figure 1.

Figure 1: Custom Controls Dialog Box

In the Available Controls list box, scroll down until you find "Microsoft MAPI Controls." Click on the check box if it isn't already checked, and click on OK. After doing so, you should see the two MAPI controls in your toolbox. (If you don't see the toolbox at all, select View, then Toolbox, from the Visual Basic menu to make it appear.) The tool icons are shown in Figure 2.

Figure 2: MAPI Tool Icons

Sending Mail

Let's get our feet wet by creating a form that allows you to enter and send a mail message. Refer to Figure 3 for control placement while you build the form, as follows:

  1. Create a new folder to contain the files for this project. Let's call the folder "SENDMSG".
  2. Start a new project in Visual Basic.
  3. Save the form as "sendmsg.frm", and save the project as "sendmsg.vbp".
  4. Set the caption of the form to "Send Message".
  5. Add the MAPI controls to your toolbox. (See above, under "Getting Started.")
  6. Add a MAPI session control to the form, and set its Name property to "MAPISession1".
  7. Add a MAPI messages control to the form, and set its Name property to "MAPIMessages1".
  8. Note: Because MAPI session and MAPI messages controls aren’t visible at runtime, it doesn’t matter where on the form you place them.

  9. Add three text boxes to the form: one for the "Send To" address, one for the subject, and one for the message itself.
  10. Set the Name properties on these text boxes to txtSendTo, txtSubject, and txtMessage, respectively.
  11. Set the Multiline property of the txtMessage text box to True.
  12. Add descriptive labels next to each text box on the form.
  13. Add a command button to the form. Set its Caption property to "Send", and its Name property to "cmdSend".
  14. Add the following code to the form load event:
  15. Private Sub Form_Load()
        MAPISession1.SignOn
    End Sub
  16. Add the following code to the form unload event:
  17. Private Sub Form_Unload(Cancel As Integer)
        MAPISession1.SignOff
    End Sub
  18. Add the following code to the command button click event:
  19. Private Sub cmdSend_Click()
        With MAPIMessages1
            .MsgIndex = -1
            .RecipDisplayName = txtSendTo.Text
            .MsgSubject = txtSubject.Text
            .MsgNoteText = txtMessage.Text
            .SessionID = MAPISession1.SessionID
            .Send
        End With
        MsgBox "Message sent!", , "Send Message"
    End Sub


Figure 3: Send Message Form

Save and run the program, then enter and send a message. If you don't get any runtime errors, then your mail message is on its way! (If you do get an error, you may have entered the recipient's address incorrectly.) That's all it takes to write a mail-enabled application. (Don't you just love Visual Basic?)

Just what have we done? As you can see from the code, the format of your mail-enabled applications will be:

  1. Establish a mail session using the MAPI session control.
  2. Do some message processing with the MAPI messages control.
  3. Release the mail session, again using the MAPI session control.

Receiving Mail

Processing received mail is only a little more complex than sending mail. You first must fetch the mail by calling the MAPI messages control’s Fetch method. This loads the control with unread messages from the user’s inbox. After calling the Fetch method, examine the control’s MsgCount property to find out how many messages were fetched, then set the MsgIndex property to tell the control which message you would like to process. Note that the MsgIndex property is 0-based. That is, the first message has an index of 0, the second message has an index of 1, and so on. An example will illustrate these concepts.

  1. Create a new folder to contain the files for this project. Let's call the folder "RECMSG".
  2. Start a new project in Visual Basic.
  3. Save the form as "recmsg.frm", and save the project as "recmsg.vbp".
  4. Set the Caption property of the form to "Receive Messages".
  5. Add the MAPI controls to your toolbox. (See above, under "Getting Started.")
  6. Add a MAPI session control to the form, and set its Name property to "MAPISession1".
  7. Add a MAPI messages control to the form, and set its Name property to "MAPIMessages1".
  8. Add three labels and a text box to the form. These will be used to show the date, the sender, the subject, and the message itself. Name the labels lblMsgDateReceived, lblMsgOrigDisplayName, and lblMsgSubject, and name the text box txtMsgNoteText. Clear out the Captions of the labels, and Text property of the text box. Refer to Figure 4 for size and placement.
  9. Set the Locked property of the text box to True, the Multiline property to True, and the ScrollBars property to 2 - Vertical.
  10. Add four more labels to provide the identifying text for the above fields. (I.e., add labels that say, "Date," "From," "Subject," and "Message."
  11. Add a label to indicate the number of messages, and which message we are currently on. Set the Name property of this label to lblMsgCount, and set the Caption property to "Message 0 of 0". Refer to Figure 4, and note where the form says, "Message 0 of 0." Place your label in a similar location.
  12. Add three command buttons to the form, and set their Names to cmdPrevious, cmdNext, and cmdClose. Set their Caption properties to Previous, Next, and Close, respectively. Position them as shown in Figure 4.
  13. Insert a procedure named FetchNewMail. Set its type to Sub, and its Scope to Public.
  14. Public Sub FetchNewMail()
        MAPIMessages1.FetchUnreadOnly = True
        MAPIMessages1.Fetch
    End Sub
  15. Insert a procedure named DisplayMessage. Set its type to Sub, and its Scope to Public.
  16. Public Sub DisplayMessage()
        lblMsgCount.Caption = "Message " & _
            LTrim(Str(MAPIMessages1.MsgIndex + 1)) & " of " & _
            LTrim(Str(MAPIMessages1.MsgCount))
        lblMsgDateReceived.Caption = MAPIMessages1.MsgDateReceived
        txtMsgNoteText.Text = MAPIMessages1.MsgNoteText
        lblMsgOrigDisplayName.Caption = MAPIMessages1.MsgOrigDisplayName
        lblMsgSubject.Caption = MAPIMessages1.MsgSubject
    End Sub
  17. Add the following code to the form’s Load event:
  18. Private Sub Form_Load()
        MAPISession1.SignOn
        MAPIMessages1.SessionID = MAPISession1.SessionID
        FetchNewMail
        DisplayMessage
    End Sub
  19. Add the following code to the cmdPrevious command button’s Click event
  20. Private Sub cmdPrevious_Click()
        If MAPIMessages1.MsgIndex > 0 Then
            MAPIMessages1.MsgIndex = MAPIMessages1.MsgIndex - 1
            DisplayMessage
        Else
            Beep
        End If
    End Sub
  21. Similarly, add the following code to the cmdNext command button’s Click event:
  22. Private Sub cmdNext_Click()
        If MAPIMessages1.MsgIndex < MAPIMessages1.MsgCount - 1 Then
            MAPIMessages1.MsgIndex = MAPIMessages1.MsgIndex + 1
            DisplayMessage
        Else
            Beep
        End If
    End Sub
  23. Add the following code to the cmdClose command button’s Click event:
  24. Private Sub cmdClose_Click()
        Unload Me
    End Sub


Figure 4: The Receive Mail Form

Save and run the project. When the form loads, the code in the Load event fetches the new mail (if any), and displays the first message. If there are multiple messages, you can use the Next button to move through them. The Previous button, of course, moves you back toward the first message.

Fetching All Messages

If you’d like to fetch all messages from the user’s inbox, set the FetchUnreadOnly property of the MAPI messages control to False before executing the Fetch method. The MsgRead property (boolean, read-only) then tells you whether any given message has previously been read. The message is automatically marked as read after the note text or attachment information has been accessed. Accessing the header information does not mark the message as read.

Attachments

Receiving Attachments

MAPI provides a count and an index for attachments, much as it does for messages. When processing received mail, your program checks the AttachmentCount property to find out how many attachments the message has. You then set the AttachmentIndex property to process each attachment in turn. Valid values for AttachmentIndex are 0 through AttachmentCount-1. After you’ve set the AttachmentIndex, you can read its attributes, as follows:

AttachmentName

This property gives you the file name of the attachment, or, if it the attachment is an OLE object, it gives you the class name of the object.

AttachmentPath

This property gives you the full path of the attached file. If you want to open or otherwise manipulate the attached file, use this property to find out where it is.

AttachmentPosition

This property specifies the attachment’s position within the body of the message. A mail program would use this information to place a representation of the attachment at the appropriate position in the displayed message text.

AttachmentType

This property specifies the type of the attachment. It is an integer that can take on one of three values, as represented by the following Visual Basic constants:

Sending Attachments

When sending mail, the above properties are used in much the same way as they are when receiving mail, except that you’re setting them instead of reading them. The notable exception is that the AttachmentIndex property can be set to anything you want. This automatically sets the AttachmentCount property to the appropriate value. (You don’t set the AttachmentCount property directly.)

Summary

In this article we’ve looked at the basics of sending and receiving mail using Microsoft’s Messaging API and Visual Basic 4.0, including processing attachments. Using this information, you can enable your applications to send and receive mail messages without human intervention.

About the Author

Dave Grundgeiger is a Microsoft Certified Solution Developer (MCSD), and is the author of .INI Master—The .INI File Difference Utility for Windows. Dave lives in Madison, Wisconsin, where he is a senior developer at Tara Software, Inc.. Dave can be reached at daveg@tarasoftware.com.

How to Send and Receive Mail Using Visual Basic 4.0
© 1997 Dave Grundgeiger. All rights reserved.
Home



Related Reading

cover

CDO and MAPI Programming with Visual Basic

by Dave Grundgeiger

CDO and MAPI Programming with Visual Basic: Developing Mail and Messaging Applications dives deep into Microsoft's Collaboration Data Objects (CDO) and the Messaging Application Programming Interface (MAPI), then moves into succinct explanations of the types of useful messaging applications that can be written in Visual Basic.


Paperback - 384 pages (October 2000)
O'Reilly & Associates; ISBN: 156592665X