|

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
{
public bool Logon( IntPtr winhandle )
public void Reset()
public void Logoff()
public void AddRecip( string name, string address, bool cc )
public void Attach( string filepath )
public bool Send( string subject, string text )
public bool Next( ref MailEnvelop env )
public string Read( string id, out MailAttach[] aat )
public bool Delete( string id )
public bool SaveAttachm( string id, string filename, string savepath )
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!
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 69 (Total in Forum: 69) (Refresh) | FirstPrevNext |
|
|
 |
|
|
Hi,
I had a requirement to send mail using the default mail client installed ,If no mail client can be found then to try using smtp relay.I had used mapi with delphi ,in that case the security warning comes up , but there is no flickering on the screen,however with c# mapi implementation I get a flickering all the time whenever we click allow on the security warning..Is there way to address it right now I am making use of sendtoback..and how do i decrease the time taken for the activation of the allow button .Is it possible?
Thanks..
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks for the sample. I've been digging around trying to find tutorials on MAPI with C# and found either unmanaged code that wouldn't work with my solution or inbox readers. None of them explained the simple function of sending a message.
I know this is old, but thanks for posting. After six years, it's still useful.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
Hi All This is really appriciated coding.but myy problem is that i want to read all mails directly from exchange server inbox.Please help me.It's very urgent for me.
ushagupta
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello, could you please help me. I can't find somewhere about my issue. Is it possible to get message priority using Simple MAPI?
Or maybe do you know other way about how to get all messages + attachments from Exchange mailbox?
Thanks Regards Andrej
modified on Wednesday, January 02, 2008 9:24:12 AM
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
Great library.
I am having problems with certain messages putting in the recipient's email address as the email type when I send a message in Outlook 2003 SP3 using this library. I went into the Mapi.cs send method and attempted to set this property to "SMTP" in the code using the code below:
//PL 10/16/2007 - set the message type lastMsg.messageType = "SMTP";
This caused Outlook to throw up a message box saying method not found.
Any ideas on how I can set the messageType property programmatically using the SimpleMapi.NET library?
Thanks, P
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I found out how to fix this. I had to append the messageType to the recipient address string like so:
recipientAddress = "SMTP:foo@bar.com"
This fixes the problem. I found this out by digging around on msdn and looking at the MAPI API documentation. The link to the recipients section where I found this is below.
http://msdn2.microsoft.com/en-us/library/ms529097.aspx
Hopefully this will help someone somewhere some day. hahaha
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Hello!
I'm using this lib for sending mails and find it great, to use the user prefered mailer. But when i try to get the mails from thunderbird client over SimpleMapi.NET, i get only the last from thunderbird received email. By trying to get the next mail ( Mapi.Net(...) ), i get an error code (last mail).
Is it possible, that some of the parameters has changed in the API?
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
it's working strange with thunderbird, anyone knows how I can get into thunderbirds folders/mails/attachments etc. thru C# ?
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Simple MAPI.NET doesn't works with Notes. It places recipient name + text + recipient name second time in my "To" field. Are there any ideas how to fix it?
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
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; } } }
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi, I would like to show an automatically generated Email to the user before sending it. So I set the MAPISendMail(...) Flag to MapiDialog (0x8). This works fine for Thunderbird as default Mail client. Outlook Express complains: "Mindestens ein Teil dieser Nachricht konnte nicht angezeigt werden." this should be in english: "At least on part of the message could not be shown." Setting the flag to 0, the Mail is sent without problems..... but I need the dialog to be shown. Any ideas how to fix this? thanks a lot Dan
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hy, here is my code example:
Where is here my error?
if (mapi.Logon(IntPtr.Zero) == false) { ...... } string mailAdress = "SMTP:a@b.de"; mapi.AddRecip(mailAdress, null, false); if (mapi.Send(subject,message)) { Console.WriteLine("Erfolgreich gesendet"); } else { Console.WriteLine("Error: {0}", mapi.Error()); }
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
I can open a new message with an attachment in Outlook 2003 and Thunderbird, but not in Outlook 2007, where it opens a new mail message with no attachments. Any ideas how to get it to work in Outlook 2007? I know it's possible since Adobe Acrobat Reader can still attach files in emails with one click.
I am using this simple code from the article:
Win32Mapi.Mapi ma = new Win32Mapi.Mapi(); ma.Logon(IntPtr.Zero); ma.Attach(@"c:\temp.txt"); ma.Send("Subjectheading", "Bodytext", false); ma.Logoff();
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
I'm using part of this class to send an automatically generated mail message. I want the application to pop up the mail form (MAPIDialog). This works great as long as I use it from the primary form. However, when I use it from a secondary form (that is click a button on the primary form to pop up a second form and then click another button to send the mail), I get my mail form to pop up but the mail form has an hourglass cursor and it appears to be hung.
Any ideas why this might happen?
Thanks.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
I also had this problem and the only workaround i found was to hide the form prior to calling MAPI.
ie,
try { // workaround a MAPI bug: // hide the window, otherwise MAPI calls below hang with a wait cursor (hourglass) Visible = false;
// ... call MAPI ... } finally { Visible = true; // restore visibility }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Thanks for this article. Well written and provides a very useful class. I am using it in one of my projects, with your name intact on the class documentation . I did document the rest of your code though ..... lol
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Anybody know how this approach for accessing Outlook emails compares with the following:
http://www.codeproject.com/useritems/extract_oulook_2003_NET.asp?forumid=280510&select=1439980&df=100&msg=1439980#xx1439978xx
Not sure if they are equivlent in functionalities or not. I also posted a similar question in the comment section of that article.
Thanks a lot!
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
I am using MS Outlook and XP. Send mail works fine (the user gets a dialog). But if the user cancels the dialog, from close button or otherwise, and Outlook is running, Outlook hangs with send/receive error message. Needs to restart Outlook
kperwaiz
|
| Sign In·View Thread·PermaLink | 3.00/5 (1 vote) |
|
|
|
 |
|
|
Change the send code to the following. If you do not log off and let the object go out of scope you have the issue you are talking about.
try { ma.AddRecip(to, null, false); if (!ma.Send(subject, body)) { MessageBox.Show("MAPISendMail failed! : " + ma.Error()); return; } MessageBox.Show("SimpleMAPICon: email sent successfully."); } finally { ma.Logoff(); }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
To start off, great code! It works very well. In my application I'm using the Outlook COM object and am able to send emails as well. But I get the infamous Outlook security popup foreach email that is sent out. The message states "A program is trying to automatically send e-mail on your behalf. Do you want to allow this?" Then you have to manually select "Yes" or "No". The above code trigers this popup as well and I was wondering if anyone figured out how to avoid this popup.
Thanks.
David www.dpatterson.net
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|