Click here to Skip to main content
15,890,043 members
Articles / Programming Languages / C#
Article

Simple MAPI.NET

Rate me:
Please Sign up or sign in to vote.
4.76/5 (57 votes)
30 Mar 2002Public Domain 438.8K   6K   80   87
Usage of the simple MAPI API.

Sample Image - simplemapidotnet.jpg

Abstract

As you know, .NET has SMTP email support built-in. For some special environments, the usage of e.g. the "Simple MAPI' API is prefered.

Details

This API can be called like most other Win32 APIs with 'PInvoke'. By reading the MSDN documentation: Platform SDK - Simple MAPI and some hints from the C++ include header file MAPI.h, we can declare the calls in C# like:

C#
[DllImport( "MAPI32.DLL", CharSet=CharSet.Ansi)]
private static extern int MAPIDeleteMail( IntPtr session, IntPtr winhandle,
                                      string id, int flags, int reserved );

For sending email with 'MAPISendMail', the structure 'MapiMessage' has to be filled with pointers to sub-structures like 'MapiRecipDesc'. For this, I used the System.Runtime.InteropServices.Marshal class:

C#
Marshal.SizeOf(), Marshal.AllocHGlobal(),
Marshal.StructureToPtr(), Marshal.PtrToStructure(),
Marshal.DestroyStructure(), Marshal.FreeHGlobal()

Most SimpleMAPI functions are 'wrapped' in a handy class (MapiApi.cs):

C#
public class Mapi
  {
  // Session
  public bool Logon( IntPtr winhandle )
  public void Reset()
  public void Logoff()

  // Sending
  public void AddRecip( string name, string address, bool cc )
  public void Attach( string filepath )
  public bool Send( string subject, string text )

  // Finding
  public bool Next( ref MailEnvelop env )

  // Reading
  public string Read( string id, out MailAttach[] aat )
  public bool Delete( string id )
  public bool SaveAttachm( string id, string filename, string savepath )

  // Addressing
  public bool SingleAddress( string label, out string name, out string addr )
  }

A small (e.g. console) client could do just this few steps:

C#
Mapi ma = new Mapi();
ma.Logon( IntPtr.Zero );
ma.AddRecip( "anybody@anywhere.org", null, false );
ma.Send( "Subject", "Mail text here" );
ma.Logoff();

Sample App

The source for a sample GUI (Windows Form) client and a console client are included in the download.

Limitations

All code was tested only on Windows XP with MS Outlook XP in the internet-mode. On this system, some security warnings show-up if accessing MAPI. Any feedback for other environments (especially Exchange) are very welcome!

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Web Developer
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralProblems setting the messageTypeProperty Pin
planzaplanza16-Oct-07 12:12
planzaplanza16-Oct-07 12:12 
GeneralRe: Problems setting the messageTypeProperty Pin
planzaplanza17-Oct-07 10:43
planzaplanza17-Oct-07 10:43 
GeneralRe: Problems setting the messageTypeProperty Pin
Vraith841-Feb-09 0:11
Vraith841-Feb-09 0:11 
QuestionGet only the last received mail from thunderbird Pin
tomthekid22-May-07 0:18
tomthekid22-May-07 0:18 
Questionwhat about thunderbird Pin
aleccc16-May-07 20:35
aleccc16-May-07 20:35 
GeneralLotus Notes 6.5 client Pin
AndreyR77722-Feb-07 4:10
AndreyR77722-Feb-07 4:10 
AnswerRe: Lotus Notes 6.5 client Pin
Aaron Browne18-Oct-07 19:46
Aaron Browne18-Oct-07 19:46 
GeneralPut message to inbox with MAPI Pin
ArsenMkrt20-Feb-07 2:28
ArsenMkrt20-Feb-07 2:28 
Hi.I write the code followed and want to put message to inbox. i have installed Outlook in my computer which is configured to exchenge server in the other machine. I want to see my message in Exchange server before send receive in my local Outlook in my case it is not like that message i get the message but only after manual send receive. Please help me to understand what is wrong i am new in MAPI. Thank you.
#include "MailGen.h"

enum { _ENTRYID, _DISPLAY_NAME, _FINDER_ENTRYID, _SUBFOLDERS };
MailGen::MailGen(void)
{
MAPIInitialize(0);
}

MailGen::~MailGen(void)
{
MAPIUninitialize();
}
BOOL MailGen::AddMailToInbox(CString strProfileName)
{
LPMAPISESSION pSession;
LPMAPIFOLDER lpProcessedFolder;
ULONG cbDefStoreEid = 0;
LPENTRYID pDefStoreEid = NULL;
ULONG ulValues;
LPSPropValue pPropValues = NULL;
CString csSearchedMBox;
LPMDB pDefMsgStore = NULL;
LPSPropValue lpRowProp = NULL;
LPSPropValue pVal = NULL;
LPMESSAGE m_pMessage;

try
{

CHECKERR(MAPILogonEx(0, // Handle to parent window
(LPTSTR)(LPCTSTR)strProfileName, // Profile name
NULL, // Password
MAPI_EXTENDED | MAPI_USE_DEFAULT | MAPI_NEW_SESSION,
// MAPI_PASSWORD_UI, // Logon flags
&pSession),"Obtain MAPI session - MAPILogonEx");

LPMAPITABLE lptMsgStores = NULL;
// Obtain a table of message stores from the session.
CHECKERR( pSession->GetMsgStoresTable(NULL, &lptMsgStores), "Obtain a table of message stores from the session - lpSession->GetMsgStoresTable" );
// Look for the default store. If you are not online,
// this is located in the Offline folder.
SizedSPropTagArray(2, tagStores) =
{
2, PR_DEFAULT_STORE, PR_ENTRYID
};
LPSRowSet pRowSetStores = 0;
SRestriction sRes;
SPropValue propStore;

propStore.ulPropTag = PR_DEFAULT_STORE;
propStore.Value.b = TRUE;
propStore.dwAlignPad = 0;

sRes.rt = RES_PROPERTY;
sRes.res.resProperty.relop = RELOP_EQ;
sRes.res.resProperty.ulPropTag = PR_DEFAULT_STORE;
sRes.res.resProperty.lpProp = &propStore;

CHECKERR( HrQueryAllRows(lptMsgStores,
(LPSPropTagArray)&tagStores,
&sRes,
0,
0,
&pRowSetStores),
"Get default message store - HrQueryAllRows");

if (pRowSetStores->cRows > 0)
{
LPSPropValue pPropStore = pRowSetStores->aRow[0].lpProps;
LPMDB pMDBDefault = 0;
//lpRowProp = pPropStore->aRow[0].lpProps;

CHECKERR( pSession->OpenMsgStore(0,
pPropStore[1].Value.bin.cb,
(LPENTRYID)pPropStore[1].Value.bin.lpb,
0,
MDB_NO_DIALOG| MAPI_BEST_ACCESS | MAPI_DEFERRED_ERRORS,
&pDefMsgStore), "Open the message store - pSession->OpenMsgStore");
CHECKERR( pDefMsgStore->GetProps(NULL,
0,
&ulValues,
&pPropValues), "pDefMsgStore->GetProps");

CHECKERR( HrGetOneProp( pDefMsgStore, PR_IPM_SUBTREE_ENTRYID, &pVal ), "HrGetOneProp - PR_IPM_SUBTREE_ENTRYID" );

//ULONG ulObjType = 0;
//CHECKERR( pDefMsgStore->OpenEntry( pVal->Value.bin.cb,
// (LPENTRYID)pVal->Value.bin.lpb,
// NULL, //We want the default interface (IMAPIFolder)
// MAPI_BEST_ACCESS, //Flags
// &ulObjType, //Object returned type
// (LPUNKNOWN *) &lpProcessedFolder), "lpMDB->OpenEntry"); //Returned folder

lpProcessedFolder = OpenInbox(pDefMsgStore);
//CHECKERR(lpProcessedFolder->CreateMessage(NULL,0,&m_pMessage),"inbox->CreateMessage()");
m_pMessage = CreateMessag(lpProcessedFolder,"FROMNAME","fromname@yahoo.com","Test Subject","Test Body");

SPropValue prop;
prop.ulPropTag=PR_MESSAGE_FLAGS;
prop.Value.l=MSGFLAG_UNSENT | MSGFLAG_FROMME;
CHECKERR(m_pMessage->SetProps(1,&prop,NULL),"m_pMessage->SetProps()");
m_pMessage->SaveChanges(FORCE_SAVE);
pSession->Logoff(NULL,0,0);
/*csSearchedMBox = "Mailbox - ";
csSearchedMBox += pPropValues[1].Value.lpszA;*/
}
}
catch( std::string& str )
{
MessageBox(NULL,str.c_str(),NULL, MB_OK | MB_ICONSTOP);
return false;
}
if (pPropValues)
MAPIFreeBuffer(pPropValues);
if (pDefMsgStore)
{
ULONG uflags = LOGOFF_NO_WAIT;
pDefMsgStore->StoreLogoff(&uflags);
pDefMsgStore->Release();
}
if (lpProcessedFolder)
{
lpProcessedFolder->Release();
}
if (pDefStoreEid)
MAPIFreeBuffer(pDefStoreEid);

if (pSession)
{
pSession->Logoff(0, MAPI_LOGOFF_SHARED, 0);
pSession->Release();
}
return true;
}
LPMESSAGE MailGen::CreateMessag(LPMAPIFOLDER folder,CString fromName,CString fromEMail,CString subject,CString body)
{
LPMESSAGE m_pMessage;
CHECKERR(folder->CreateMessage(NULL,0,&m_pMessage),"inbox->CreateMessage()");
set_SenderName(m_pMessage,fromName);
set_SenderEmail(m_pMessage,fromEMail);
set_Subject(m_pMessage,subject);
set_Body(m_pMessage,body);
return m_pMessage;
}
void MailGen::CHECKERR( HRESULT hr, const char* msg )
{
if( hr != S_OK ){
char buf[11];
itoa( hr, buf, 16 );
std::string err("FAILED with error - ");
err += buf;
err += ", ";
err += msg ? msg : "";
throw err;
}
}
LPMAPIFOLDER MailGen::OpenInbox(LPMDB m_pMsgStore)
{
if(!m_pMsgStore) return NULL;

ULONG cbEntryID;
LPENTRYID pEntryID;
DWORD dwObjType;
LPMAPIFOLDER pFolder;

CHECKERR(m_pMsgStore->GetReceiveFolder(NULL,0,&cbEntryID,&pEntryID,NULL),"m_pMsgStore->GetReceiveFolder()");
m_pMsgStore->OpenEntry(cbEntryID,pEntryID, NULL, MAPI_BEST_ACCESS ,&dwObjType,(LPUNKNOWN*)&pFolder);
MAPIFreeBuffer(pEntryID);

return pFolder;
}
void MailGen::set_Subject(LPMESSAGE m_pMapiMessage,LPCTSTR subject)
{
CString strSubject = subject;
if(strSubject.GetLength()>0 && m_pMapiMessage) {
SPropValue prop;
prop.ulPropTag=PR_SUBJECT;
prop.Value.LPSZ=(TCHAR*)subject;
m_pMapiMessage->SetProps(1,&prop,NULL);
}
}

void MailGen::set_SenderName(LPMESSAGE m_pMapiMessage,LPCTSTR senderName)
{
CString strSenderName=senderName;
if(strSenderName.GetLength() > 0 && m_pMapiMessage) {
SPropValue prop;
prop.ulPropTag=PR_SENDER_NAME;
prop.Value.LPSZ=(TCHAR*)senderName;
m_pMapiMessage->SetProps(1,&prop,NULL);
}
}

void MailGen::set_SenderEmail(LPMESSAGE m_pMapiMessage,LPCTSTR senderEmail)
{
CString strSenderEmail=senderEmail;
if(strSenderEmail.GetLength()>0 && m_pMapiMessage) {
SPropValue prop;
prop.ulPropTag=PR_SENDER_EMAIL_ADDRESS;
prop.Value.LPSZ=(TCHAR*)senderEmail;
m_pMapiMessage->SetProps(1,&prop,NULL);
}
}

void MailGen::set_Body(LPMESSAGE m_pMapiMessage,LPCTSTR body)
{
CString strBody=body;
if(strBody.GetLength()>0 && body) {
LPSTREAM pStream=NULL;
if(m_pMapiMessage->OpenProperty(PR_BODY, &IID_IStream, 0, MAPI_MODIFY | MAPI_CREATE, (LPUNKNOWN*)&pStream)==S_OK) {
pStream->Write(body,(ULONG)(_tcslen(body)+1)*sizeof(TCHAR),NULL);
pStream->Release();
pStream = NULL;
}
}
}

QuestionOutlook Express MapiDialog causes error Pin
daues2-Feb-07 4:39
daues2-Feb-07 4:39 
QuestionError: MAPI login failure [3] Pin
daniel9916-Nov-06 9:26
daniel9916-Nov-06 9:26 
QuestionOutlook 2007 attachments? Pin
Richard__8-Nov-06 1:39
Richard__8-Nov-06 1:39 
QuestionWhy hourglass from secondary form on send? Pin
c-a-b-31-Aug-06 2:06
c-a-b-31-Aug-06 2:06 
AnswerRe: Why hourglass from secondary form on send? Pin
vzxcasdfgasd14-Nov-06 13:15
vzxcasdfgasd14-Nov-06 13:15 
GeneralGreat Article Pin
ben_5-Jun-06 9:27
ben_5-Jun-06 9:27 
GeneralGreat article, very useful Pin
Ranjan Banerji29-Apr-06 7:47
Ranjan Banerji29-Apr-06 7:47 
QuestionHow to compare this approach with using the MAPI namespace as in this article? Pin
tank2096-Apr-06 12:42
tank2096-Apr-06 12:42 
GeneralMS Outlook Hangs Pin
kperwaiz13-Feb-06 19:01
kperwaiz13-Feb-06 19:01 
GeneralRe: MS Outlook Hangs Pin
Jeff Lindholm15-Sep-06 3:28
Jeff Lindholm15-Sep-06 3:28 
QuestionHow do you avoid the Outlook security popup? Pin
youngDev26-Oct-05 10:45
youngDev26-Oct-05 10:45 
AnswerRe: How do you avoid the Outlook security popup? Pin
Antony M Kancidrowski15-Mar-06 6:10
Antony M Kancidrowski15-Mar-06 6:10 
AnswerRe: How do you avoid the Outlook security popup? Pin
sinanju29-Aug-06 1:31
sinanju29-Aug-06 1:31 
AnswerRe: How do you avoid the Outlook security popup? Pin
John Boero30-May-07 11:38
John Boero30-May-07 11:38 
GeneralWonderfull, Need Help Pin
Md Saleem Navalur26-Jul-05 21:09
Md Saleem Navalur26-Jul-05 21:09 
GeneralMAPISendDocuments Pin
Jim Rogers16-Jun-05 5:18
Jim Rogers16-Jun-05 5:18 
GeneralSending HTML messages Pin
Thomas at Wendia11-Apr-05 0:23
Thomas at Wendia11-Apr-05 0:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.