Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to send e-mail using MAPI session

COM and Automation

How to send e-mail using MAPI session

by  Mike Gagnon  Posted    (Edited  )
Note: The following code was tested with CDO version 1.21. The following is aslo intended for use with a mail server (ie: Exchange Server), although it also works directly (For simpler code refer to faq184-1768)

These links are also deemed helpful to understand "Differences Between CDO, Simple MAPI, and Extended MAPI"
http://support.microsoft.com/default.aspx?scid=kb;EN-US;200018
"MAPI Is Not Suitable for HTML Messages"
http://support.microsoft.com/default.aspx?scid=kb;en-us;268440
"Where to Acquire the CDO Libraries (all versions)"
http://support.microsoft.com/default.aspx?scid=kb;EN-US;171440

[ul][li] Checking for the CDO version installed:
Code:
oSession = CreateObject('MAPI.Session')
oSession.Logon() && Unless you know the profile, this will prompt you to select one.
*oSession.Logon('Microsoft Outlook Internet Settings')
MESSAGEBOX('CDO version installed is '+trans(oSession.Version))
[/li]

[li]Discover the CDO configuration properties.
Code:
Clear
CDOCfg=Createobject('CDO.Configuration')
For Each oField In CDOCfg.Fields
	If !"postpassword" $  oField.Name
		? oField.Name + " "+Transform(oField.Value)
	Endif
Next
[/li]

[li]Discover the properties of a CDO message.
Code:
Clear
oCDO=Createobject('CDO.Message')
For i = 1 To Amembers(aa,oCDO,3)
	? i, aa(i,1), aa(i,2), aa(i,3)
Next
[/li]

[li]Bringing up the address book
Code:
oSession = CreateObject('MAPI.Session')
oSession.Logon('Microsoft Outlook Internet Settings','<password>')
oSession.AddressBook(,'Please select a Name',.t.,,0)
[/li]
[li]Sending a simple message (no attachement)
Code:
oSession = CreateObject("MAPI.Session")
oSession.Logon("Microsoft Outlook Internet Settings",<password>)
oNewMessage=oSession.Outbox.messages.add()
oNewMessage.Subject = "This is an e-mail using CDO"
oNewMessage.Text = "Welcome to the world of CDO"
oNewMessage.DeliveryReceipt = .T. &&Optional, forces a receipt send back
oRecipient = oNewMessage.Recipients.Add()
oRecipient.Name = "John Doe" && This name must appear in your address book.
oRecipient.Resolve && If name does not appear this will cause an error.
oNewMessage.Update()
oNewMessage.Send(1,0,0) && The 1 will save a copy of the message in your sent items folder of Outlook.
oSession.Logoff()
[/li][li]Sending a message with an attachement
Code:
#DEFINE CdoFileData  1 && ReadFromFile method Attachment is a file (Default value) 
#DEFINE CdoFileLink  2 &&Source property  Attachment is a link to a file 
#DEFINE CdoOLE  3 &&ReadFromFile method  Attachment is an OLE object 
#DEFINE CdoEmbeddedMessage  4 &&ID property of the Message object to be embedded  Attachment is an embedded message 
#DEFINE  CdoDefaultFolderOutbox  2
oSession = CreateObject('MAPI.Session')
oSession.Logon('Microsoft Outlook Internet Settings','<password>')
oFolder=oSession.GetDefaultFolder(CDODefaultFolderOutBox)
oMessage=oFolder.Messages.add()
oAttachment = oMessage.Attachments.Add()
oAttachment.Position = 0  && Important to position the attachement
oAttachment.Type = CdoFileData
oAttachment.ReadFromFile( 'c:\autoexec.bat')
oAttachment.Source = 'c:\autoexec.bat'
oAttachment.Name = 'autoexec.bat'
oMessage.Update()
oMessage.Send()
oSession.LogOff
[/li]
[li]Accessing different folders
Here is an example of accessing the Calendar folder:
Code:
#DEFINE CdoDefaultFolderCalendar  0
#DEFINE CdoDefaultFolderContacts  5
#DEFINE CdoDefaultFolderDeletedItems  4
#DEFINE CdoDefaultFolderInbox  1
#DEFINE CdoDefaultFolderJournal  6
#DEFINE CdoDefaultFolderNotes  7
#DEFINE Const CdoDefaultFolderOutbox  2
#DEFINE CdoDefaultFolderSentItems  3
#DEFINE CdoDefaultFolderTasks  8
oSession = CreateObject("MAPI.Session")
oSession.Logon("Microsoft Outlook Internet Settings",<password>)
oFolder =OSession.GetDefaultFolder(CdoDefaultFolderCalendar)
[/li]
[li]To retrieve appointements from the Calendar folder
Code:
#DEFINE CdoDefaultFolderCalendar  0
oSession = CreateObject("MAPI.Session")
oSession.Logon("Microsoft Outlook Internet Settings","<password>")
oFolder=oSession.GetDefaultFolder(CdoDefaultFolderCalendar)
oAppointmentItems = oFolder.Messages
For Each oAppointment In oAppointmentItems
  MESSAGEBOX(TRANSFORM( oAppointment.StartTime))
Next
[/li][li]Retrieve all attachments from a message
Code:
#DEFINE CdoDefaultFolderInbox  1
oSession = CreateObject("MAPI.Session")
oSession.Logon("Microsoft Outlook Internet Settings")
oFolder=oSession.GetDefaultFolder(CdoDefaultFolderInbox)
oMessages = oSession.Inbox.Messages
&& Get first message of inbox
oMessage = oMessages.Item(1)
For Each oAttachment In oMessage.Attachments
  strAttachName = oAttachment.Name
  oAttachment.WriteToFile("c:\"+ strAttachName)
Next
[/li][li]Sending a message with high priority
Code:
#DEFINE CdoDefaultFolderInbox  1
#DEFINE CdoPR_PRIORITY_LOW -1
#DEFINE CdoPR_PRIORITY_NORMAL 0
#DEFINE CdoPR_PRIORITY_HIGH 1
#DEFINE CdoPR_PRIORITY  "&amp;H00260003"
oSession = CreateObject("MAPI.Session")
oSession.Logon("Microsoft Outlook Internet Settings")
oNewMessage=oSession.Outbox.messages.add()
oField = oNewMessage.Fields
oField.Add(CdoPR_PRIORITY,CdoPR_PRIORITY_HIGH)
oRecipient = oNewMessage.Recipients.Add
oRecipient.Name = "Cesar" && Name has to exist
oRecipient.Resolve()
oNewMessage.Update()
*oNewMessage.Send()
[/li]
[li]How to send a fax with an attachement.
Code:
objSession = CreateObject("Mapi.Session")
objSession.Logon ()
objMessage = objSession.Outbox.Messages.Add 
objMessage.Subject = "Test" 
objMessage.Text = "This is a test" 
objRecipient = objMessage.Recipients.Add 
objRecipient.Name = "[FAX:5555551111]" 
objRecipient.Type = 1 
objRecipient.Resolve ()
objMessage.Attachments.Add( "test.txt",0,  1, "C:\test.txt" )
objMessage.Send ()
objSession.Logoff
[/li]
[li]Form sample of sending mail using mapi session
Code:
PUBLIC ofrmmapi
ofrmmapi=NEWOBJECT("frmmapi")
ofrmmapi.Show
RETURN
DEFINE CLASS frmmapi AS form
	Top = 0
	Left = 0
	Height = 433
	Width = 686
	DoCreate = .T.
	BackColor = RGB(192,192,192)
	Caption = "Form1"
	Name = "frmMapi"
	ADD OBJECT shape1 AS shape WITH ;
		BackStyle = 0, ;
		Curvature = 20, ;
		Height = 265, ;
		Left = 12, ;
		Top = 9, ;
		Width = 325, ;
		Name = "Shape1"
	ADD OBJECT shape2 AS shape WITH ;
		BackStyle = 0, ;
		Curvature = 20, ;
		Height = 265, ;
		Left = 348, ;
		Top = 9, ;
		Width = 325, ;
		Name = "Shape2"
	ADD OBJECT olemessage AS olecontrol WITH ;
		Top = 0, ;
		Left = 612, ;
		Height = 100, ;
		Width = 100, ;
		TabIndex = 14, ;
		AddressResolveUI = .T., ;
		Name = "oleMessage",;
		OleClass = "MSMAPI.MAPIMessages.1"
	ADD OBJECT olesession AS olecontrol WITH ;
		Top = 0, ;
		Left = 552, ;
		Height = 100, ;
		Width = 100, ;
		TabIndex = 13, ;
		DownloadMail = .F., ;
		Name = "oleSession",;
		OleClass = "MSMAPI.MAPISession.1"
	ADD OBJECT cmdsend AS commandbutton WITH ;
		Top = 336, ;
		Left = 588, ;
		Height = 29, ;
		Width = 94, ;
		Caption = "Send", ;
		TabIndex = 11, ;
		Name = "cmdSend"
	ADD OBJECT lstfilename AS listbox WITH ;
		RowSourceType = 7, ;
		Height = 205, ;
		Left = 360, ;
		TabIndex = 8, ;
		Top = 45, ;
		Width = 300, ;
		Name = "lstFilename"
	ADD OBJECT cmdclose AS commandbutton WITH ;
		Top = 384, ;
		Left = 588, ;
		Height = 29, ;
		Width = 94, ;
		Caption = "Close", ;
		TabIndex = 12, ;
		Name = "cmdClose"
	ADD OBJECT txtrecipient AS textbox WITH ;
		ControlSource = "", ;
		Format = "K", ;
		Height = 25, ;
		Left = 24, ;
		TabIndex = 2, ;
		Top = 40, ;
		Width = 301, ;
		Name = "txtRecipient"
	ADD OBJECT lstrecipients AS listbox WITH ;
		Height = 157, ;
		Left = 24, ;
		Sorted = .T., ;
		TabIndex = 10, ;
		Top = 93, ;
		Width = 301, ;
		Name = "lstRecipients"
	ADD OBJECT label1 AS label WITH ;
		AutoSize = .T., ;
		BackStyle = 0, ;
		Caption = "List of Recipients:", ;
		Height = 18, ;
		Left = 24, ;
		Top = 71, ;
		Width = 112, ;
		TabIndex = 9, ;
		Name = "Label1"
	ADD OBJECT label2 AS label WITH ;
		AutoSize = .T., ;
		BackStyle = 0, ;
		Caption = "Enter Recipient Name to Add:", ;
		Height = 18, ;
		Left = 24, ;
		Top = 22, ;
		Width = 187, ;
		TabIndex = 1, ;
		Name = "Label2"
	ADD OBJECT label3 AS label WITH ;
		AutoSize = .T., ;
		BackStyle = 0, ;
		Caption = "Select Attachments:", ;
		Height = 18, ;
		Left = 360, ;
		Top = 22, ;
		Width = 126, ;
		TabIndex = 7, ;
		Name = "Label3"
	ADD OBJECT edtnotetext AS editbox WITH ;
		Height = 73, ;
		Left = 12, ;
		TabIndex = 6, ;
		Top = 348, ;
		Width = 565, ;
		ControlSource = "THISFORM.oleMessage.MsgNoteText", ;
		Name = "edtNoteText"
	ADD OBJECT label4 AS label WITH ;
		AutoSize = .T., ;
		BackStyle = 0, ;
		Caption = "Message Text:", ;
		Height = 18, ;
		Left = 12, ;
		Top = 324, ;
		Width = 91, ;
		TabIndex = 5, ;
		Name = "Label4"
	ADD OBJECT txtsubject AS textbox WITH ;
		ControlSource = "THISFORM.oleMessage.MsgSubject", ;
		Format = "K", ;
		Height = 25, ;
		Left = 72, ;
		TabIndex = 4, ;
		Top = 284, ;
		Width = 505, ;
		Name = "txtSubject"
	ADD OBJECT label5 AS label WITH ;
		AutoSize = .T., ;
		BackStyle = 0, ;
		Caption = "Subject:", ;
		Height = 18, ;
		Left = 12, ;
		Top = 288, ;
		Width = 52, ;
		TabIndex = 3, ;
		Name = "Label5"
	PROCEDURE Init
		WITH THISFORM
			WAIT WINDOW NOWAIT "Please wait ... Logging Into Mail" NOCLEAR

			* Signon to mail
			.oleSession.Signon

			* If the session ID is not valid, do not allow the form to load
			IF .oleSession.SessionID &gt; 0
				.oleMessage.SessionID = .oleSession.SessionID
			ELSE
				WAIT WINDOW NOWAIT "Form Cannot Load: Login Failed"
				RETURN .F.
			ENDIF
			* Start a new message
			.oleMessage.Compose
		ENDWITH
		WAIT CLEAR
	ENDPROC
	PROCEDURE cmdsend.Click
		WAIT WINDOW NOWAIT NOCLEAR "Sending Message ... "

		WITH THISFORM
			* Add an attachment if a file has been selected
			IF !EMPTY(.lstFilename.Value)
				* You must provide the complete path to the attachment
				.oleMessage.AttachmentPathname = .lstFilename.List(2) + .lstFilename.Value
			ENDIF

			* If the subject, note text, or recipient list is empty, a Compose
			* message dialog will be displayed.
			IF EMPTY(.txtSubject.Value) ;
				OR EMPTY(.edtNoteText.Value) ;
				OR (.lstRecipients.ListCount = 0)
					.oleMessage.Send(1)
			ELSE
				.oleMessage.Send(0)
			ENDIF

			* Reset all values
			.txtRecipient.Value = ""
			.lstRecipients.Clear
			.txtSubject.Value = ""
			.edtNoteText.Value = ""

			* Start a new message
			.oleMessage.Compose
		ENDWITH
		WAIT WINDOW NOWAIT "Message Sent!  New Message Ready"
	ENDPROC
	PROCEDURE cmdclose.Click
		* Sign off of mail and release the form
		THISFORM.oleSession.Signoff
		THISFORM.Release
	ENDPROC
	PROCEDURE txtrecipient.Valid
		* Only add a recipient if one has been typed in (to prevent blank recipients)
		IF !EMPTY(ALLTRIM(THIS.Value))
			WITH THISFORM
				* Increment the Recipient index
				.oleMessage.RecipIndex = ;
					IIF(.lstRecipients.Listcount = 0, 0, ;
					.oleMessage.RecipIndex + 1)

				* Set the Recipient name and resolve
				.oleMessage.RecipDisplayName = ALLTRIM(THIS.value)
				.oleMessage.ResolveName

				* Add the name to the Listbox on the form
				.lstRecipients.AddItem(THISFORM.oleMessage.RecipDisplayName)
			ENDWITH
		ENDIF
	ENDPROC
	PROCEDURE edtnotetext.Click
		* Trim the contents
		THIS.Value = ALLTRIM(THIS.Value)
	ENDPROC
	PROCEDURE txtsubject.Valid
		* Trim the contents
		THIS.Value = ALLTRIM(THIS.Value)
	ENDPROC
ENDDEFINE
[/li][/ul]


Mike Gagnon
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top