Thursday, October 12, 2006

Extended MAPI - What is it and why should I care

There are many ways of working with and/or sending emails from Visual FoxPro. Most of these ways I have explored in my previous blog entries: MAPI, Outlook, CDOSYS, CDO NTS, Shell, WinExec, w3JMail, BLAT, and EsSmtp. The entry dealing with MAPI uses what is known as "Simple MAPI" which is not the same thing, nor as powerful as, Extended MAPI (sometimes referred to as just MAPI). For a little more information regarding MAPI you can refer to this Wikipedia entry.

In short, Extended MAPI allows a developer to manipulate in code any email client (such as Outlook) that supports or has implemented MAPI. This includes sending, receiving, and reading emails as well as a whole host of other features dealing with email and retrieving information regarding email in MAPI-aware email clients. But, what really excited me about Extended MAPI in the first place is that it allows us to circumvent the Outlook security warning seen in the image below...

OutlookSecurityWarning.gif

If you've ever used Simple MAPI to send emails from your application through a patched copy of Outlook then the above dialog box is no stranger to you or your users. This dialogue is very disconcerting to the users for obvious reasons (just read what the dialog box says). So many developers sending email via Outlook using Simple MAPI have spent a good deal of money (upwards of $200 or more) to get rid of it in their applications - as evidenced here and here.

I thought that just for this reason alone it would be nice if VFP developers could use Extended MAPI free and easy in Visual FoxPro. So, I began writing the VFPExMAPI.FLL a few weeks ago and got it to a point where it was truly useful earlier today.

VFPExMAPI Library

The FLL is not currently a complete implementation of Extended MAPI, but it will be someday and for right now it allows the sending of emails with attachments through Outlook (or any other email client that has implemented the Extended MAPI interface) which is a pretty common task in today's Visual FoxPro applications. It should be noted that this FLL borrows heavily from the work of Noel Dillabough out on Code Project.

Possible future features

  • Expose entire Extended MAPI functions/features via this FLL

What you can do (if you want)

I would appreciate feedback regarding this FLL and bug reports when problems are encountered. I think that's a fair trade if you've found this FLL useful and it will help me improve it for the benefit of the entire VFP Community. Also, if you have any suggestions for improving this FLL (such as new features) please don't hesitate to post a comment here in this blog or send me an email.

That having been said, here is the download, sample VFP code, and the documentation for the FLL...


VFP Extended MAPI FLL:

VFPExMAPI FLL Download (14 KB approx.)


VFP Extended MAPI Sample Code:

***************************
*!* See the following link for more information
*!* http://www.sweetpotatosoftware.com/SPSBlog/PermaLink,guid,baccc84d-4d91-458b-a839-ad03662dfc34.aspx
***************************

#Define MAPI_ORIG 0
#Define MAPI_TO 1
#Define MAPI_CC 2
#Define MAPI_BCC 3

#Define IMPORTANCE_LOW 0
#Define IMPORTANCE_NORMAL 1
#Define IMPORTANCE_HIGH 2

#Define FNEVCRITICALERROR 0X00000001
#Define FNEVNEWMAIL 0X00000002
#Define FNEVOBJECTCREATED 0X00000004
#Define FNEVOBJECTDELETED 0X00000008
#Define FNEVOBJECTMODIFIED 0X00000010
#Define FNEVOBJECTMOVED 0X00000020
#Define FNEVOBJECTCOPIED 0X00000040
#Define FNEVSEARCHCOMPLETE 0X00000080
#Define FNEVTABLEMODIFIED 0X00000100
#Define FNEVSTATUSOBJECTMODIFIED 0X00000200

#Define WM_USER 0x0400

#DEFINE FLLPATH "E:\SPS Blog\vfpexmapi71\vfpexample\"
#DEFINE RECIP "
craig@sweetpotatosoftware.com"
Public goMapiEvent
Local lcAttachment, lcHTML, lcRTF, lcText
Set Library To Locfile(FLLPATH + "
vfpexmapi.fll")

*****************************
*!* Send Text Email
*****************************
m.lcText = "
Here's a plain text email."
?"
Sending Text Email"
?EMCreateMessage("
Text Test", m.lcText, IMPORTANCE_NORMAL)
?EMAddRecipient(EMAILRECIP, MAPI_TO)
*!* More recipients could be added here
*!* Create a temp file to attach - just for example purposes
m.lcAttachment = ADDBS(SYS(2023)) + SYS(2015) + "
.TXT"
=STRTOFILE("
Visual FoxPro Rocks!", m.lcAttachment, 0)
?EMAddAttachment(m.lcAttachment)
*!* More attachments could be added here
?EMSend() && don't send yet, just put it in the Outbox

*****************************
*!* Send HTML Email
*****************************
TEXT TO m.lcHTML NOSHOW
<html>
<body>
<p>Here's an HTML email.</p>
<ul>
<li>The</li>
<li><a href="
http://www.sweetpotatosoftware.com/SPSBlog/">SPS Weblog</a></li>
<li>is Back.</li>
</ul>
<p>Visual FoxPro Rocks!</p>
</body>
</html>
ENDTEXT
?
?"Sending HTML Email"
?EMCreateMessageEx("HTML Test", m.lcHTML, IMPORTANCE_HIGH)
?EMAddRecipient(EMAILRECIP, MAPI_TO)
?EMAddAttachment(m.lcAttachment)
?EMSend() && don't send yet, just put it in the Outbox

*****************************
*!* Send RTF Email
*****************************
TEXT TO m.lcRTF NOSHOW
{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
Here is a {\b Rich Text Format} email.\par
}
ENDTEXT
?
?"Sending RTF Email"
?EMCreateMessageEx("RTF Test", m.lcRTF, IMPORTANCE_LOW)
?EMAddRecipient("someone@somedomain.com", MAPI_TO)
?EMAddAttachment(m.lcAttachment)
?EMSend(.T.) && Send all 3 emails now
*****************************
*!* Display Email Form to User
*****************************
m.lcText = "User can decide whether to send this or not."
?
?"Displaying Email"
?EMCreateMessage("Text Test", m.lcText, IMPORTANCE_NORMAL)
?EMAddRecipient(EMAILRECIP, MAPI_TO)
?EMDisplay() && display email form - returns .T./.F. indicating whether user sent email
*****************************
*!* Clean up the temp file we created as an attachment
*****************************
IF FILE(m.lcAttachment)
ERASE (m.lcAttachment)
ENDIF
SET LIBRARY TO

*****************************
*!* MAPI Bindevent Example
*****************************
Set Library To Locfile(FLLPATH + "vfpexmapi.fll")
m.lcText = "User can decide whether to send this or not."
Clear
?
?"Displaying Email"
?EMCreateMessage("Text Test", m.lcText, IMPORTANCE_NORMAL)
?EMAddRecipient(EMAILRECIP, MAPI_TO)
m.goMapiEvent = Createobject("EMEvents")
Bindevent(_vfp.HWnd,WM_USER + 1, goMapiEvent, "ExtendedMapiEvent") && custom application events are between WM_USER and 0x7FFF
?EMBindEvent(FNEVNEWMAIL)
?EMSend(.T.) && After this go do a Send/Receive in Outlook so that the New Mail event fires
*!* Calling SET LIBRARY TO here would unhook the event, so we don't do it

*****************************
Define Class EMEvents As Custom
*!* Class to bind the _vfp WM_USER + 1 window message to
*****************************
Function ExtendedMapiEvent(HWnd,Msg,WPARAM,LPARAM)
Local lnType, lcInfoStruct, lnStructMembersTotal, lnStructCounter, lcEventMessage
m.lnType = CToBin(Sys(2600,Lparam,4),"4RS")
*!* More work to do on this, an FLL function that dev can send LPARAM
*!* to will be created and an array or object will be created in VFP
Do Case
Case m.lnType = 1 && ERROR_NOTIFICATION 20 bytes
m.lcEventMessage = "ERROR_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = 5
Case m.lnType = 2 && NEWMAIL_NOTIFICATION 28 bytes
m.lcEventMessage = "NEWMAIL_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = 7
Case Bitand(m.lnType,252) > 0 && OBJECT_NOTIFICATION 40 bytes
m.lcEventMessage = "OBJECT_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = 10
Case m.lnType = 256 && TABLE_NOTIFICATION ??? bytes
m.lcEventMessage = "TABLE_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = ???
Case m.lnType = 512 && STATUS_OBJECT_NOTIFICATION 16 bytes
m.lcEventMessage = "STATUS_OBJECT_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = 4
Otherwise && EXTENDED_NOTIFICATION 12 bytes
m.lcEventMessage = "EXTENDED_NOTIFICATION event has occurred!"
m.lnStructMembersTotal = 3
Endcase
?m.lcEventMessage
*!* Comment out the line below to leave the event bound
EMUnbindEvents() && Now remove the hook (SET LIBRARY TO does an implicit hook removal as well)
*!* LOCAL ARRAY laValues(m.lnStructMembersTotal)
*!* FOR m.lnStructCounter = 1 TO m.lnStructMembersTotal
*!* laValues(m.lnStructCounter) = CTOBIN(SYS(2600,LPARAM + 8 + ((m.lnStructCounter - 1) * 4),4),"4RS")
*!* ENDFOR
Endfunc
Enddefine


VFP Extended MAPI Documenation:


Function EMCreateMessage()

Signature: EMCreateMessage(cSubject, cBody, nImportance)

Parameters:

cSubject - subject line of the email

cBody - body of the email

nImportance - level of importance for the email - valid values for this parameter are as follows:

0 = Low Importance
1 = Normal Importance
2 = High Importance

Return Value:

Logical - indicating whether the message was successfully created - .T. for success and .F. for failure

Remarks:

This function creates the email message that is going to be sent and should be called first before adding recipients and/or attachments.


Function EMCreateMessageEx()

Signature: EMCreateMessageEx(cSubject, cHtmlOrRtfBody, nImportance)

Parameters:

cSubject - subject line of the email

cHtmlOrRtfBody - body of the email formatted in HTML or RTF

nImportance - level of importance for the email - valid values for this parameter are as follows:

0 = Low Importance
1 = Normal Importance
2 = High Importance

Return Value:

Logical - indicating whether the message was successfully created - .T. for success and .F. for failure

Remarks:

This function creates the email message that is going to be sent and should be called first before adding recipients and/or attachments. This function is an advanced version of EMCreateMessage providing for either HTML or RTF within the body of the email. Ensure that the cHtmlOrRtfBody parameter contains complete HTML or RTF as shown in the example above. In short, the opening and closing tags are required as they are used to determine what format was used for the body.


Function EMAddRecipient()

Signature: EMAddRecipient(cRecipientEmailAddress, nRecipientType)

Parameters:

cRecipientEmailAddress - subject line of the email

nRecipientType - defines the type of recipient to be added - valid values for this parameter are as follows:

0 = Original
1 = To
2 = CC
3 = BCC

Return Value:

Logical - indicating whether the recipient was successfully added - .T. for success and .F. for failure

Remarks:

This function should be called after the EMCreateMessage function.


Function EMAddAttachment()

Signature: EMAddAttachment(cFileName)

Parameters:

cFileName - full path and file name of the attachment to be added

Return Value:

Logical - indicating whether the attachment was successfully added - .T. for success and .F. for failure

Remarks:

This function should be called after the EMCreateMessage function.


Function EMSend()

Signature: EMSend([lSendImmediately])

Parameters:

lSendImmediately - .T. or .F. value indicating whether the email message should be sent immediately or remain in the Outbox (see disclaimer in Remarks below)

Return Value:

Logical - indicating whether the email was successfully placed into the email client send queue (outbox) - .T. for success and .F. for failure

Remarks:

This function should be called after the EMCreateMessage function. Also, it is important to note that just because the file has been placed to the outbox of the email client and is waiting to be sent does not mean that the email will be immediately sent. When the email actually gets sent (right away or after a certain delay) is dependent on the user-defined settings in the email client for sending email that is sitting in the send queue. If you wish to send the email(s) in the outbox immediately (regardless of user settings) you can pass .T. for the lSendImmediately parameter. The email(s) in the outbox can be sent immediately regardless of whether or not the user currently has their email client open.

Be aware that the autosend feature provided by the lSendImmediately parameter does not work for Outlook 2002-2003. If anyone knows a way around this limitation I would appreciate it if you would contact me. For more details on this limitation see http://support.microsoft.com/kb/317412.


Function EMDisplay()

Signature: EMDisplay()

Parameters: None

Return Value:

Logical - indicating whether the user sent the email from the compose window or cancelled the operation by clicking the close button - .T. for sent and .F. for cancelled.

Remarks:

This function should be called after the EMCreateMessage function. Rather than submitting the email directly to the outbox, this function allows you to show the client's email composition window. The email can be displayed whether or not the user has their email client open.


Function EMBindEvent()

Signature: EMBindEvent(nEvent)

Parameters:

nEvent - numeric value indicating the type of MAPI Notification Event to watch for. The following is a list of possible values:

  • Critical Error = 1
  • New Email Arrival = 2
  • Object Created = 4
  • Object Deleted = 8
  • Object Modified = 16
  • Object Moved = 32
  • Object Copied = 64
  • Search Complete = 128
  • Table Modified = 256
  • Status Object Modified = 512
  • Reserved For MAPI = 1024
  • Extended = 2048

Return Value:

Logical - indicating whether the event was successfully bound - .T. for success and .F. for failure

Remarks:

This function is most easily understood by running the example provided. When the bound event is fired it sends a message to the _VFP window that can easily be bound to using Visual FoxPro's BindEvent. Information regarding the notfication event that fired can be extracted from the LPARAM parameter. This is just a beginning. Eventually the library will provide other methods of easily extracting the information from all the pointers and structures. For now I would like developers to get a feel for how this works.

It should be noted that for now only a single MAPI Notification Event can be bound to at a time. Calling the EMBindEvent function releases the previous hook (if it exists) before instituting the new one. In the future simultaneous hooks will be provided for.

Special thanks to Bo Durban for providing a workaround that made this method possible.


Function EMUnbindEvents()

Signature: EMUnbindEvents()

Parameters: None

Return Value:

Logical - indicating whether a hook that was created using EMBindEvent was removed - .T. for success and .F. for failure

Remarks:

This function should be called after the EMBindEvent function when you wish to remove the hook. Issuing SET LIBRARY TO also releases any active hook that may exist. Crashing or closing out of a system without removing an active MAPI Notification Event hook can cause the user's email client to become unstable. It is strongly recommended that a hook are removed as soon as you are through using it using EMUnbindEvents. Calling the EMUnbindEvents function when no hook is active does not cause any problems or errors.

Thursday, October 12, 2006 8:53:46 PM (Central Daylight Time, UTC-05:00)  #    Comments [20]
Thursday, October 12, 2006 9:18:53 PM (Central Daylight Time, UTC-05:00)
Awesome! I've been meaning to look into this and just never got around to it. Now I don't have to...

Dude, I have two words for you: Caffeine Patch...

Oh and you need to hook up an error handler to your blog - it gives a yellow screen of death when you put some invalid characters like a an HTML [g] in...
Thursday, October 12, 2006 9:56:49 PM (Central Daylight Time, UTC-05:00)
Rick,
Thanks for the "Awesome!" and for the tip regarding the Caffeine Patch. (Are those available on the West Wind Web Store?) I hear you on the lame yellow error screen coming up - not very professional/polished. Though I've been meaning to update to the latest copy of dasBlog and also fix a few things like the issue you mention, the only thing I seem to have succeeded at on that front is procrastination.
Sunday, October 15, 2006 6:33:06 PM (Central Daylight Time, UTC-05:00)
Prof. Boyd,

I just ran the sample code and it worked perfectly (as expected!). One a curious note, a change of the current default directory (to an unintended "\Program Files\Common Files\System\MSMAPI\"... 4-digit language code) is taking place after execution.

Perhaps, there could be a function to launch the default email client (like "mailto:" does), to force messages posted to the OutBox be actually sent or another variant of the same, a function to state "you have X messages in X-software pending delivery".

Other than that... it seems like you produce code (and document it!) like Mozart wrote operas, that is as if taking musical dictation rather than painfully/meditatively composing.

With your blessing, this is an .FLL I will implement at once in my applications. Long live the Fox... and THANK YOU!!!!
Tuesday, October 24, 2006 6:17:08 PM (Central Daylight Time, UTC-05:00)
great tool my work order software now can send emails with having to hit yes and yes
yes..............
Patrick O'Hara
Friday, November 03, 2006 1:30:37 AM (Central Daylight Time, UTC-05:00)
I am writing to post a fervent request for a .DISPLAY() equivalent function to the already wonderful VFP Extended MAPI Library. Is this possible?

The alternative (to bring the RTF control plus all the user-expected toolbars, etc etc.) would not need to be considered/implemented if such display function where made available within your FLL.

PLEASE consider this plea!! and Thanks Thanks Thanks!!!

Kenneth Tamayo

*******************************************************************

oOutLookObject = CreateObject("Outlook.Application")
oEmailItem = oOutLookObject.CreateItem(0)

WITH oEmailItem
.Recipients.Add("someone@somedomain.com")
.Subject = "x subject line"
.Importance = 1
.DISPLAY()
ENDWITH
Friday, November 24, 2006 5:59:45 AM (Central Standard Time, UTC-06:00)
set library to vfpexmapi.fll from vfp6.0 & vfp7.0 produces the error
"invalid libarry"
Sepos Loizos
Friday, November 24, 2006 10:42:27 AM (Central Standard Time, UTC-06:00)
Hi Sepos,

In order to use this FLL with earlier versions of VFP you will need to include the msvcr71.dll. This is a required runtime file and without it you will get the error "invalid library".
Sunday, November 26, 2006 9:13:44 PM (Central Standard Time, UTC-06:00)
Thanks Graig,

I will try it tomorrow. I believe that I must include the msvcr71.dll in the working directory.
Sepos Loizos
Monday, November 27, 2006 1:39:53 PM (Central Standard Time, UTC-06:00)
Hi Graig,

I have placed the msvcr71.dll in working directory, windows\system and keeps giving me the same "invalid library"
sepos loizos
Saturday, December 09, 2006 7:05:03 PM (Central Standard Time, UTC-06:00)
Hello Craig,

This is a nice and usefull piece of software.
However when testing it I discovered a major problem.
Sending attachments to non-outlook users (pmail, outlook express..) gives them a useless attachment "winmail.dat" i.s.o the attachment send to them. Receiving outlook users don't have this problem.



eddy dirckx
Sunday, December 17, 2006 8:33:13 AM (Central Standard Time, UTC-06:00)
How could I get the email address of the sender with this library (i.e if I am sending a mail I would like to obtain my email adress). Actually I'm trying to trigger a pseudo email with this libray so as to capture the email addresses of users on a network.

Any suggestions?

Jacan
Wednesday, December 20, 2006 12:09:54 AM (Central Standard Time, UTC-06:00)
I have exactly the same problem as Eddy, it was a show stopper for me. Any ideas how to avoid this problem?
Otherwise a beautiful piece of software...
Victor Espinoza
Thursday, December 21, 2006 2:07:06 PM (Central Standard Time, UTC-06:00)
Sepos,

I'm sorry you are still having problems. I am pretty sure your problem is related to the msvcr71.dll not being in the path where the FLL can find it. Try putting it in the system32 folder or put it in the same directory as the FLL. "Invalid Library" errors with FLLs are almost always caused by missing C runtimes.

Jacan,
The email is sent using the default send account of the MAPI-aware email client. Such as in Outlook, if you look in the accounts you will see that one of them is marked as default. While Extended MAPI might provide some way to query the email client for the default account, this FLL isn't designed with that functionality in mind.

Eddy and Victor,

I don't like show stoppers, so I've posted a new version of the FLL (just this morning). Just re-download the FLL from the link provided in this blog entry and see if it is fixed. A quick Google search for "winmail.dat" provided a wealth of information on why and how that happens - a few real interesting reads there. In any event, please test the new version of the FLL and comment back here with your results. Thanks.
Friday, December 22, 2006 8:34:35 AM (Central Standard Time, UTC-06:00)
Craig,

The new FLL solved the "winmail.dat" problem.
Thanks for this useful piece of software and great support !!!

eddy dirckx
Monday, December 25, 2006 3:54:20 PM (Central Standard Time, UTC-06:00)
Craig

Thanks for the quick response and fix. Great piece of software ... Thanks again!
Victor
Friday, February 02, 2007 6:57:10 PM (Central Standard Time, UTC-06:00)
Hey Craig - hope things are good.

FYI - the FLL is still resetting the user's current directory to the MAPI\1033 folder.

But otherwise works awesome!
Thursday, March 15, 2007 6:19:41 PM (Central Daylight Time, UTC-05:00)
Craig,

Thanks a lot for all your work.

I noticed a wrong description for Parameters:

cRecipientEmailAddress - subject line of the email

which is obviously not the subject, but the recipient.

Also I have a question - how do you send HTML type of e-mails with your library?
Naomi
Friday, June 08, 2007 9:45:08 PM (Central Daylight Time, UTC-05:00)
Hi, I gave it a try, worked fine and as expected. The one thing that would make it really valuable is if it allowed html email content rather than plain text.

Thanks for your great efforts for the Fox Community!
:-

Gene
Gene
Friday, August 24, 2007 10:01:31 AM (Central Daylight Time, UTC-05:00)
Can i use this fll with outlook express?
Michael
Monday, October 29, 2007 6:52:44 PM (Central Daylight Time, UTC-05:00)
It's asking for select outlook as default mail client, but I have outlook express working.
Doesn't work with outolook express?
Thanks!
Rodrigo Juarez
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):


 

Archive

<November 2008>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456