?
Solved

C#: Error An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mapi33.dll

Posted on 2005-04-14
2
Medium Priority
?
4,699 Views
Last Modified: 2008-01-09
Code:
public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();
                  MAPI33.MAPI.Initialize(null);
                  string[] problems;
                  MAPI33.Helpers.Message.Send(MAPI33.Helpers.Message.SendFlags.UseDefaultProfile,
                        "",
                        new string[] { "JoeD@mail.com" },
                        null,
                        null,
                        "MAPI33",
                        "Hello World !",
                        null,
                        out problems);
                  MAPI33.MAPI.Uninitialize();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }


An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mapi33.dll
Additional information: File or assembly name System, or one of its dependencies, was not found.
An unhandled exception of type 'System.TypeInitializationException' occurred in mapi33.dll
Additional information: The type initializer for "__MAPI33__INTERNALS__.Unknown" threw an exception.

I already added mapi33.dll as a reference to my windows application, when i compile, above errors shows up.
Anyone knows what happen? thanks!

0
Comment
Question by:grace627
2 Comments
 
LVL 2

Accepted Solution

by:
masoncooper earned 2000 total points
ID: 13811296
grace627:
I saw your comment over at Q_21151088, it looks like you were trying to do what I was trying to do a while back.

I made some changes to muellerfan's function so that you can send messages via extended mapi, and even attach files.  
As much as I hate to just cut/paste code to solve a problem, promise me you'll take the time to learn how this all works.  

To send an email, just declare an instance of MAPIHelper.Helper and from that object, call SendEmail, there are 3 overloads from you to choose from

This is the contents of a C# project with a class called MAPIHelper
--------------------------MAPIHelper.CS--------------------------
using System;
using System.IO;
using MAPI33;
using MAPI33.MapiTypes;


namespace MAPIHelper
{
                //MAPIHelper: Developed by Mason Cooper with the help of muellerfan
      /// <summary>
      /// Allows the sending and receiving of messages over Extended MAPI
      /// </summary>
      public class Helper
      {

            enum oneoff{_DISPLAY_NAME, _ADDRTYPE, _EMAIL_ADDRESS, _RECIPIENT_TYPE, NUM_RECIP_PROPS};

            #region SendEmail Overloads
            
            /// <summary>
            /// Sends an email using the current MAPI profile
            /// Assumes no attachments
            /// </summary>
            /// <param name="from">Name that appears in the From field</param>
            /// <param name="to">Recipient of Message</param>
            /// <param name="subject">Subject of the message</param>
            /// <param name="body">HTML-Formatted Body of message</param>
            public void SendEmail(string from, string to, string subject, string body)
            {
                  string[] attachments = new string[0];
                  SendEmail(from,to,subject,body,attachments,true,null);
            }

            /// <summary>
            /// Sends an email using a specified MAPI profile
            /// Assumes no attachments
            /// </summary>
            /// <param name="from">Name that appears in the From field</param>
            /// <param name="to">Recipient of Message</param>
            /// <param name="subject">Subject of the message</param>
            /// <param name="body">HTML-Formatted Body of message</param>
            /// <param name="attachByVal">True:Include attachments in body. False:Link to attachments from UNC.</param>
            /// <param name="attachments">Array of paths to attachments, must be UNC if attachByVal is False</param>
            /// <param name="MAPIProfileName">Name of MAPI Profile to use</param>
            public void SendEmail(string from, string to, string subject, string body,
                  string MAPIProfileName)//Look at line 63
            {
                  string[] attachments = new string[0];
                  SendEmail(from,to,subject,body,attachments,true,MAPIProfileName);
            }

                  
            #endregion


            /// <summary>
            /// Sends an email using Extended MAPI
            /// </summary>
            /// <param name="from">Name that appears in the From field</param>
            /// <param name="to">Recipient of Message</param>
            /// <param name="subject">Subject of the message</param>
            /// <param name="body">HTML-Formatted Body of message</param>
            /// <param name="attachByVal">True:Include attachments in body. False:Link to attachments from UNC.</param>
            /// <param name="attachments">Array of paths to attachments, must be UNC if attachByVal is False</param>
            /// <param name="MAPIProfileName">Name of MAPI Profile to use</param>
            public void SendEmail(string from, string to, string subject, string body,
                  string[] attachments, bool attachByVal, string MAPIProfileName)
            {  
                  Error hr;
                  IMAPISession session;
                  MAPI33.MAPI.TYPE objtype;
                  MAPI33.IUnknown unk;
                  IMAPITable tblMsgStores;
                  ENTRYID storeeid = null;
                  Tags [] itags;
                  IMsgStore store;
                  ENTRYID outboxid = null;
                  IMAPIFolder outbox;
                  IAddrBook ab;
                  MAPI33.SPropProblem [] probs;
               
                  //OPEN MAPI33.MAPI
                  hr = MAPI33.MAPI.Initialize(null);
                  if (MAPIProfileName != null && MAPIProfileName != "")
                  {
                        hr = MAPI33.MAPI.LogonEx(IntPtr.Zero,MAPIProfileName,
                              null,   MAPI33.MAPI.FLAGS.Extended |MAPI33.MAPI.FLAGS.LogonUI |MAPI33.MAPI.FLAGS.NoMail,    
                              out session);
                  }
                  else
                  {
                        
                        hr = MAPI33.MAPI.LogonEx(IntPtr.Zero, null,
                              null,   MAPI33.MAPI.FLAGS.Extended |MAPI33.MAPI.FLAGS.LogonUI |MAPI33.MAPI.FLAGS.NoMail,    
                              out session);
                  }
                  //FIND THE DEFAULT STORE
                  hr = session.GetMsgStoresTable(0, out tblMsgStores);
               
                  MAPI33.MapiTypes.Value[,] rows;
                  itags = new Tags[] {Tags.PR_ENTRYID, Tags.PR_DEFAULT_STORE};
                  tblMsgStores.SetColumns(itags, IMAPITable.FLAGS.Default);
                  hr = tblMsgStores.QueryRows(50, 0, out rows);
                  tblMsgStores.Dispose();

                  for (int i=0; i <= rows.GetUpperBound(0); i++)
                  {
                        bool isdefault = ((MAPI33.MapiTypes.MapiBoolean)rows[i,1]).Value;
                        if (isdefault)
                        {    
                              storeeid = new ENTRYID((byte[])((MapiBinary)rows[i,0]).Value);
                              break;
                        }
                  }

                  // NOW WE CAN OPEN OUR MESSAGE STORE
                  //hr = session.OpenMsgStore(IntPtr.Zero, storeeid, Guid.Empty,IMAPISession.FLAGS.Modify, out store);
                  hr = session.OpenEntry(storeeid, Guid.Empty, IMAPISession.FLAGS.Modify, out objtype, out unk);
                  store = (IMsgStore)unk;
                  unk.Dispose();

                  //GET THE OUTBOX FOLDER
                  itags = new Tags[] {Tags.PR_IPM_OUTBOX_ENTRYID};
                  MAPI33.MapiTypes.Value[] pvals = new MAPI33.MapiTypes.Value[0];
                  hr = store.GetProps(itags, 0, out pvals);
                  for (int k=0; k < pvals.Length; k++)
                        outboxid = new ENTRYID((byte[])((MapiBinary)pvals[k]).Value);
               
                  hr = store.OpenEntry(outboxid, Guid.Empty, IMsgStore.FLAGS.Modify, out objtype, out unk);
                  outbox = (IMAPIFolder)unk;
                  unk.Dispose();

                  //CREATE THE NEW MESSAGE
                  IMessage message;
                  hr = outbox.CreateMessage(Guid.Empty, 0, out message);
                  hr = session.OpenAddressBook(IntPtr.Zero, Guid.Empty, 0, out ab);

                  //ADD RECIPIENTS
                  MAPI33.ADRENTRY [] sendto = new ADRENTRY[1];
                  sendto[0] = new ADRENTRY((int)oneoff.NUM_RECIP_PROPS);
                  sendto[0].PropVals[0] = new MapiString(Tags.PR_DISPLAY_NAME, to);
                  sendto[0].PropVals[(int)oneoff._ADDRTYPE] = new MapiString(Tags.PR_ADDRTYPE, "SMTP");
                  sendto[0].PropVals[(int)oneoff._EMAIL_ADDRESS] = new MapiString(Tags.PR_EMAIL_ADDRESS, to);
                  sendto[0].PropVals[(int)oneoff._RECIPIENT_TYPE] = new MAPI33.MapiTypes.MapiInt32(Tags.PR_RECIPIENT_TYPE,1);
                   
                  hr = ab.ResolveName(IntPtr.Zero, 0, null, ref sendto);
               
                  //IF RECIPIENT IS NOT FOUND, WE CREATE A ONE-OFF
                  if (hr == MAPI33.Error.NotFound)
                  {
                        ENTRYID oneoffentry;
                   
                        hr = ab.CreateOneOff(to, "SMTP", to, 0, out oneoffentry);
                   
                        sendto[0] = new ADRENTRY((int)oneoff.NUM_RECIP_PROPS + 1);
                        sendto[0].PropVals[(int)oneoff._DISPLAY_NAME] = new MapiString(Tags.PR_DISPLAY_NAME, to);
                        sendto[0].PropVals[(int)oneoff._ADDRTYPE] = new MapiString(Tags.PR_ADDRTYPE, "SMTP");
                        sendto[0].PropVals[(int)oneoff._EMAIL_ADDRESS] = new MapiString(Tags.PR_EMAIL_ADDRESS, to);
                        sendto[0].PropVals[(int)oneoff._RECIPIENT_TYPE] = new MAPI33.MapiTypes.MapiInt32(Tags.PR_RECIPIENT_TYPE,1);
                        sendto[0].PropVals[(int)oneoff.NUM_RECIP_PROPS] = new MAPI33.MapiTypes.MapiBinary(Tags.PR_ENTRYID, oneoffentry.ab);
                  }
               
                  hr = message.ModifyRecipients(IMessage.FLAGS.ModrecipAdd, sendto);
               
                  //ADD SUBJECT
                  MAPI33.MapiTypes.Value[] props = new MAPI33.MapiTypes.Value[1];
                  props[0] = new MapiString(Tags.PR_SUBJECT, subject);
                  hr = message.SetProps(props, out probs);
           
                  //ADD ATTACHMENT(s)
                  foreach(string atchmt in attachments)
                  {
                        if (atchmt!= null && atchmt != "")//Catch empty string, in array
                        {
                    MAPI33.IAttachment att;
                              int attNum;
                              MAPI33.SPropProblem[] errors;
                              hr = message.CreateAttach(Guid.Empty,0,out attNum,out att);
                              Console.WriteLine(string.Concat("Attachment Created: " ,hr.ToString()));
                              props = new MAPI33.MapiTypes.Value[5];
                              if (!System.IO.File.Exists(atchmt))
                              {
                                    message.Dispose();
                                    ab.Dispose();
                                    outbox.Dispose();
                                    store.Dispose();
                                    throw new Exception(string.Concat("Cannot find Attachment :",
                                          atchmt));
                              }


                              /*Attachbyval:
                               * If True, the user wishes to include the file within the message
                               *                  so PR_ATTACH_DATA_BIN contains byte array of file
                               * If False, PR_ATTACH_METHOD is By Reference and PR_ATTACH_PATHNAME
                               *                  will be UNC Path to file
                              */
                              if (attachByVal)
                              {
                                    props[0] = new MapiInt32(Tags.PR_ATTACH_METHOD,1);//1=ATTACH_BY_VALUE
                                    props[1] = new MapiBinary(Tags.PR_ATTACH_DATA_BIN,LoadFile(atchmt));
                              }
                              else
                              {
                                    props[0] = new MapiInt32(Tags.PR_ATTACH_METHOD,2);//1=ATTACH_BY_REFERENCE
                                    props[1] = new MapiString(Tags.PR_ATTACH_PATHNAME,atchmt);
                              }

                              props[2] = new MapiString(Tags.PR_DISPLAY_NAME,getFileName(atchmt));
                              props[3] = new MapiString(Tags.PR_ATTACH_LONG_FILENAME,getFileName(atchmt));
                              props[4] = new MapiString(Tags.PR_ATTACH_FILENAME,getFileName(atchmt));
                              
                              //Commit Properties
                              hr = att.SetProps(props, out errors);
                              hr = att.SaveChanges(0);
                              //Be 100% sure to manually dispose all objects when we're done
                              att.Dispose();
                              }
                  }

                  //ADD BODY
                  body = body.Replace("\n", "<br>");
                  props = new MAPI33.MapiTypes.Value[1];
                  props[0] = new MapiString(Tags.PR_BODY_HTML, body);
                  hr = message.SetProps(props, out probs);


                  //SET FLAGS
                  props = new MAPI33.MapiTypes.Value[1];
                  props[0] =  new MapiBoolean(Tags.PR_DELETE_AFTER_SUBMIT, true);
                  hr = message.SetProps(props, out probs);


                  //SEND MESSAGE
                  hr = message.SubmitMessage(0);
                  ab.Dispose();
                  message.Dispose();
                  outbox.Dispose();
                  store.Dispose();

                  message = null;
                  
 
                  session.Logoff(IntPtr.Zero, 0);
                  session.Dispose();
                  MAPI33.MAPI.Uninitialize();
            Console.WriteLine("Message Successfully Sent");
            }


            #region Helper Functions
            /// <summary>
            /// Reads the contents of a file into a byte array
            /// </summary>
            /// <param name="_FileName">Path to file</param>
            /// <returns>Array of bytes</returns>
            private byte[] LoadFile(string _FileName)
            {
                  System.IO.FileStream file;
                  file = new System.IO.FileStream(_FileName, FileMode.Open, FileAccess.Read);
                  byte[] fileAry = ReadFully(file);
                  file.Close();

                  return fileAry;
            }

            /// <summary>
            /// Reads data from a stream until the end is reached. The
            /// data is returned as a byte array. An IOException is
            /// thrown if any of the underlying IO calls fail.
            /// </summary>
            /// <param name="stream">The stream to read data from</param>
            private static byte[] ReadFully (Stream stream)
            {
                  byte[] buffer = new byte[32768];
                  using (MemoryStream ms = new MemoryStream())
                  {
                        while (true)
                        {
                              int read = stream.Read (buffer, 0, buffer.Length);
                              if (read <= 0)
                                    return ms.ToArray();
                              ms.Write (buffer, 0, read);
                        }
                  }
            }

            public static string getFileName(string Path)
            {
            return (Path.Remove(0,Path.LastIndexOf("\\")+1));
            }

            #endregion
      }
}

---------------------END--MAPIHelper.CS--------------------------

Also, a side note, For the attachments, I included the ability to Attach By Reference.  Within my company, I can keep a large file on a network share, and attach byref, it's transparent to the recipient, but they actually open the attachment from a UNC instead of the inbox, that saves TONS of disk space and takes the load off the exchange server.  And the best part is that it's built into the Extended-MAPI Spec.
0
 

Author Comment

by:grace627
ID: 13821037
Wonderful! Thanks so much for your answer!
I am taking the time to learn how it works now. thanks!
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will help to fix the below error for MS Exchange server 2010 I. Out Of office not working II. Certificate error "name on the security certificate is invalid or does not match the name of the site" III. Make Internal URLs and External…
This article describes how to import Lotus Notes Contacts into Outlook 2016, 2013, 2010 and 2007 etc. with a few manual steps. You can easily export and migrate Lotus Notes contacts into Microsoft Outlook without having to use any third party tools.
This Experts Exchange video Micro Tutorial shows how to tell Microsoft Office that a word is NOT spelled correctly. Microsoft Office has a built-in, main dictionary that is shared by Office apps, including Excel, Outlook, PowerPoint, and Word. When …
CodeTwo Sync for iCloud (http://www.codetwo.com/sync-for-icloud?sts=6554) automatically synchronizes your Outlook 2016, 2013, 2010 or 2007 folders with iCloud folders available via iCloud Control Panel. This lets you automatically sync them with…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question