0% found this document useful (0 votes)
14 views

Gs 9711

This document discusses how to add email functionality to Windows applications using ActiveX DLLs and the Microsoft Active Messaging library. It provides code samples for sending email from a Visual Basic application using Active Messaging. The code creates a MAPI session object, adds a message to the outbox folder, sets the message properties like subject and recipients, and sends the message with one line of code. Active Messaging simplifies adding email capabilities with its hierarchical object model and ease of use compared to previous methods.

Uploaded by

Lasp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Gs 9711

This document discusses how to add email functionality to Windows applications using ActiveX DLLs and the Microsoft Active Messaging library. It provides code samples for sending email from a Visual Basic application using Active Messaging. The code creates a MAPI session object, adds a message to the outbox folder, sets the message properties like subject and recipients, and sends the message with one line of code. Active Messaging simplifies adding email capabilities with its hierarchical object model and ease of use compared to previous methods.

Uploaded by

Lasp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

BEGINNER

G E T T IN G S T A R T E D

Add E-Mail to Your Apps


by Chris Barlow

sers have come to expect all Windows applications to feature the ability to
Encapsulate e-mail send e-mail. If your application creates a data file, you definitely want to
provide a menu item that attaches that data file to an e-mail message and
functionality into sends the message.
Only a few years ago, it was difficult to mail-enable your application. You needed to
install an e-mail client, such as MSMail, as well as several Messaging Application
ActiveX DLLs for Programming Interface (MAPI) DLLs to link to a MAPI service provider, such as a
Microsoft Mail (MSMail) post office or Exchange. Today, e-mail is ubiquitous and most
computers are set up for e-mail. The interfaces have been simplified, and your
easy reuse later. Windows Messaging or Outlook client can communicate with your organization’s

Session
Click & Retrieve
Source

CODE! AddressLists Collection Folder (Inbox or Outbox)

AddressList Folders Collection

AddressEntries
Collection Folder

AddressEntry Messages Collection

Message

Attachments Collection

Attachment

Recipients Collection

Recipient

Chris Barlow is president and CEO of


SunOpTech, a developer of manufactur- AddressEntry
ing decision-support and supply chain
applications. Chris, who is a frequent
speaker at VBITS, Tech•Ed, and DevDays Simplified Object Model. The object model for the Active Messaging Library
and has been featured in two Microsoft FIGURE 1 is a hierarchical model. In this figure, each indented object is considered a child
videos, holds degrees from Harvard Busi- of the object under which it is indented. An object is the parent of every object at the next
ness School and Dartmouth College. Reach level of indention under it. For example, an Attachments collection and a Recipients
Chris at [email protected] or collection are both child objects of a Message object, and a Messages collection is a parent
through SunOpTech’s Web server at object of a Message object. However, a Messages collection is not a parent object of a
www.SunOpTech.com. Recipients collection.

72 NOVEMBER 1997 Visual Basic Programmer’s Journal http://www.windx.com


BEGINNER
G E T T IN G S TA R T E D

Exchange Server through MAPI service Active Messaging gives you easy ac- SendWithAM
providers such as CompuServe, Microsoft cess to sending and receiving e-mail End Sub
Network, and America Online, or through from within a Visual Basic application.
any Simple Mail Transfer Protocol (SMTP)/ It also gives you full access to the fold- Calling a procedure from your button
Post Office Protocol 3 (POP3) mail server. ers within your information store. To Click events rather than writing the code
In previous articles, I suggested you send e-mail from an application with inline gives you more flexibility to call the
use the MAPI controls that come with Vi- Active Messaging, start a new Visual procedure from a different place in your
sual Basic, or direct calls to the MAPI DLL, Basic 5 project and design a simple form application.
to add e-mail functionality to your apps [“A to send e-mail. Make sure you create The object model for Active Messag-
New Outlook on MAPI,” VBPJ November text-box controls for the recipient, sub- ing is simple. The Session object is the
1996]. Now, with the release of Outlook ject, message, and attachment, as well starting point for all use of the Active
8.01 and Exchange 5.0, you should use the as a CommandButton control labeled Messaging components. Begin an Active
new Active Messaging 1.1 components re- Send. Select the References menu item Messaging session by creating a
leased by Microsoft because Active Mes- on the Project menu, and add a refer- MAPI.Session object. All other objects are
saging is easier to use, more flexible, and ence to the Microsoft Active Messaging derived from the Session object (see Fig-
more powerful. You can download these 1.1 Object Library. Double-click on the ure 1 for a simplified version of the object
components from Microsoft’s Web site at Send button and add this code to call model from the Active Messaging help
ftp://ftp.microsoft.com/services/technet/ the new procedure SendWithAM: file). For example, you can create an out-
samples/boes/bo/mailexch/exchange/ going message by adding a Message ob-
appfarm/actmsg.exe. Private Sub butSend_Click() ject to the Messages collection in the

mLoggedOn = True
Exit Function
End If
Option Explicit 'logon failed so try to get default profile
Public Profile As String Profile = GetDefaultProfile
Private mLoggedOn As Boolean If Len(Profile) Then oSession.Logon ProfileName:=Profile
If Err = 0 Then
Public Property Get LoggedOn() As Boolean mLoggedOn = True
LoggedOn = mLoggedOn Exit Function
End Property End If
'finally try a normal logon
Private Sub Class_Initialize() oSession.Logon
On Error Resume Next If Err = 0 Then
Set oSession = CreateObject("MAPI.Session") mLoggedOn = True
If oSession Is Nothing Then Exit Function
Err.Raise vbObjectError + Err, "SOTMapi", _ End If
"Create failed"
Exit Sub Err.Raise vbObjectError + Err, "SOTMapi", "Logon failed"
End If Logon = Err
End Sub End Function

Private Sub Class_Terminate() Public Function SendQuick(SendTo$, Subject$, Optional _


oSession.Logoff Message$ = "", Optional Attach$ = "") As Long
Set oSession = Nothing Dim oMessage As Message
End Sub On Error Resume Next
If Not mLoggedOn Then Logon
Public Function Logon_ If Err Then Exit Function
(Optional sProfile As String = "") As Long Set oMessage = oSession.Outbox.Messages.Add
'first try to logon with passed profile With oMessage
On Error Resume Next .Subject = Subject
If Len(sProfile) Then .Text = " " & Message
oSession.Logon ProfileName:=sProfile End With
If Err = 0 Then With oMessage.Recipients.Add
mLoggedOn = True .Name = SendTo
Profile = oSession.ProfileName .Type = mapiTo
Exit Function .Resolve
End If End With
End If If Len(Attach) Then
'then try Profile property With oMessage.Attachments.Add
If Len(Profile) Then .Position = 1
oSession.Logon ProfileName:=Profile .Type = mapiFileData
If Err = 0 Then .Name = Attach
mLoggedOn = True .ReadFromFile Attach
Exit Function End With
End If End If
End If oMessage.Send
'then try to logon to existing session SendQuick = Err
oSession.Logon ShowDialog:=False, NewSession:=False End Function
If Err = 0 Then

MAPIClass Class Module. This class module contains the properties and methods for the new class. Design the Logon
LISTING 1method to perform a “quiet” logon—first, by using a given profile name from the class’s Profile property, then by trying to log
on to an existing session, and finally by finding the default profile from the registry.

http://www.windx.com Visual Basic Programmer’s Journal NOVEMBER 1997 73


Dim oMessage As Message ment to work with the Recipient object
On Error Resume Next without having to dimension a variable
Set oSession = _ to hold the Recipient object. Call the
CreateObject("MAPI.Session") Resolve method to change the text
If oSession Is Nothing Then name to a valid e-mail address. If you
Exit Sub enter an ambiguous name, a dialog ap-
End If pears to resolve the name manually:
oSession.Logon
If Err Then Exit Sub With oMessage.Recipients.Add
.Name = txtTo
Add a new outgoing message object, .Type = mapiTo
and set the Subject and Text properties .Resolve
from the text-box controls: End With
Send the Message. This is how
FIGURE 2 your message looks in your Set oMessage = _ If you enter a file path in the Attachment
Outbox after you send it with these oSession.Outbox.Messages.Add text-box control, add an Attachment object
procedures. Notice that the icon for the With oMessage to the message and set the Position, Type,
attachment is located in the first position of .Subject = txtSubject and Name properties. The Position prop-
the mail message text. .Text = " " & txtNoteText erty determines where to place the icon for
End With the attached file in the text portion of the
Outbox folder. message. Use the ReadFromFile method to
Add code to dimension a Session ob- Add a Recipient object to this mes- read the file contents as an attachment:
ject and a Message object, create the sage, and set the Name and Type prop-
MAPI session, and call the Logon method erties. Your e-mail message can have If Len(txtAttach) Then
of the Session object: many recipients. The Type property With oMessage.Attachments.Add
controls whether they appear in the .Position = 1
Private Sub SendWithAM() To: or the CC: section of the message. .Type = mapiFileData
Dim oSession As Object You can use the With…End With state- .Name = txtAttach
.ReadFromFile txtAttach
End With
End If

Finally, send the message and log off


the session (see Figure 2):

oMessage.Send
oSession.Logoff
End Sub

This is all you need to do to mail-enable


your application, but let’s go a step fur-
ther. Messaging code has changed dra-
matically over the past few years and will
undoubtedly continue to change. Rather
than write an application that calls these
properties and methods explicitly, why
not encapsulate this functionality into an
ActiveX DLL with a simple class your appli-
cations can call? This way, you won’t need
to change your applications the next time
messaging changes because changing the
DLL will upgrade your application.

ACTIVE MESSAGING CLASS


Select the Add Project menu item from the
Project menu and choose ActiveX DLL. Right-
click on the class module to display the
Properties tab, change the name of the class
to MAPIClass, and change Instancing to Multi-
Use. When creating any class, you need to
plan the properties and methods of the class.
With this simple example class, you only
need two properties and two methods.
The LoggedOn property is True if the
class is logged onto a messaging session.
BEGINNER
G E T T IN G S T A R T E D

This should be a read-only property of the for the text-box controls (see Listing 1).
class, so you need a private variable to You should design the Logon method
hold the value and a Property Get proce- to perform a “quiet” logon—first, by using
dure to return the value. You can use the a given profile name from the class’s Pro-
Profile property to specify the profile to file property, then by trying to log on to an
use when logging on. Because the applica- existing session, and finally by finding the
tion using the class sets the Profile prop- default profile from the registry. This last
erty, the property can be a simple public step can be a bit complicated. Article
string variable. The Logon method calls Q171422 in the Microsoft Knowledge Base
the Session object’s Logon method, but (www.microsoft.com/kb) provides some
has the capability to find the default profile good sample code that I included in the
if one is not specified. The SendQuick GetDefaultProfile procedure in the class’s
method accepts the message’s recipient, module. Download Listing 2 from the free,
subject, text, and attachment as arguments, Registered Level of The Development Ex-
and provides a single simple call to send a change (see the Code Online box for de-
message with no more than one attach- tails). The class should display a dialog
ment to a single recipient. box only if these quiet attempts fail (see
You might find that you want to ex- Listing 1).
pand this class to allow for multiple re- Now build your ActiveX DLL, and
cipients and multiple attachments, but change your test application to call your
let’s start with this simple class for now. new class by adding the SendMailClass
Dimension the public Profile property and procedure to the form and changing the
the private mLoggedOn variable in the code in the Send button’s Click event to
class module. Write the Property Get pro- call the new procedure:
cedure to return the value of this private
variable: Private Sub SendWithClass()
Dim MyMapi As New MAPIClass
Option Explicit On Error Resume Next
Public Profile As String If MyMapi.SendQuick(txtTo, txtSubject, _
Private mLoggedOn As Boolean txtNoteText, txtAttach) = 0 Then
If Err Then
Public Property Get LoggedOn() As _ MsgBox "Send Failed " & Err
Boolean Else
LoggedOn = mLoggedOn MsgBox "Message Sent"
End Property End If
Else
Create the MAPI Session object in the MsgBox "Send Failed"
class’s Initialize event, and log off the End If
session in the Terminate event: End Sub

Private Sub Class_Initialize() Notice that your app doesn’t need to


On Error Resume Next set the profile or call the Logon method
Set oSession = _ explicitly because the SendQuick method
CreateObject("MAPI.Session") calls the Logon method if the session is not
If oSession Is Nothing Then logged on. You’ve now wrapped the Active
Err.Raise vbObjectError + Err, _ Messaging library with your own class. If
"SOTMapi", "Create failed" all your applications use your class, it will
Exit Sub be easy for you to maintain compatibility
End If as messaging continues to evolve.
End Sub

Private Sub Class_Terminate()


Code Online
You can find all the code published in this
oSession.Logoff issue of VBPJ on The Development Exchange
Set oSession = Nothing (DevX) at http://www.windx.com. For details,
End Sub please see “Get Extra Code in DevX’s Premier
Club” in Letters to the Editor.
Because the SendQuick method is simi- Add E-Mail to Your Apps
lar to the SendWithAM you wrote, copy
that code and paste it into your class mod- Locator+ Codes
ule within the public SendQuick method. Listings ZIP file plus Listing 2 (free Registered
Level): VBPJ1197
Modify the code to check the value of the Listings for this article plus Listing 2 and
mLoggedOn variable, and call the Logon the VB files that let you mail-enable your
method if the session is not logged on. The application (subscriber Premier Level):
message will be sent as before, except you GS1197P
need to substitute the method’s arguments

75 NOVEMBER 1997 Visual Basic Programmer’s Journal http://www.windx.com

You might also like