65.9K
CodeProject is changing. Read more.
Home

Simple MAPI.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (56 votes)

Mar 31, 2002

Public Domain
viewsIcon

448540

downloadIcon

6047

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:

  [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:

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

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

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:

  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!