title: Sending mail via Outlook API - Outlook closes to fast
body: <p>I wrote a class to send emails via outlook automated. Everything is fine beside the small case, that the mail is generated, put to the "outgoing" folder and then outlook is closed. The closing is so fast, that the mail is sended once I start outlook the next time.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class MyMail
  {
      private const double WaitingForSending = 30.0;
  
      #region Local variables
      public bool SSL_Encryption = true;
      public System.Collections.Generic.List&lt;System.Net.Mail.MailAddress&gt; Address = null;
      public System.Collections.Generic.List&lt;System.Net.Mail.MailAddress&gt; CC = null;
      public System.Collections.Generic.List&lt;System.Net.Mail.MailAddress&gt; BCC = null;
      public System.Collections.Generic.List&lt;string&gt; AttachmentFileName = null;
      public string Body = "";
      public string Subject = "";
      #endregion
  
  
      public void SendMail()
      {
          double Waited = .0;
          string fAddress = string.Empty;
  
          if (this.Address == null) { return; }
          Microsoft.Office.Interop.Outlook.Application OL = new Microsoft.Office.Interop.Outlook.Application();
  
          Microsoft.Office.Interop.Outlook.MailItem Mail = (Microsoft.Office.Interop.Outlook.MailItem)OL.CreateItem(OlItemType.olMailItem);
          Mail.Subject = this.Subject;
          if (this.Address != null) { foreach (System.Net.Mail.MailAddress MA in this.Address) { fAddress += MA.Address + "; "; } Mail.To = fAddress; fAddress = string.Empty; }
          if (this.CC != null) { foreach (System.Net.Mail.MailAddress MA in this.CC) { fAddress += MA.Address + "; "; } Mail.CC = fAddress; fAddress = string.Empty; }
          if (this.BCC != null) { foreach (System.Net.Mail.MailAddress MA in this.BCC) { fAddress += MA.Address + "; "; } Mail.BCC = fAddress; fAddress = string.Empty; }
          Mail.Body = this.Body;
          if (this.AttachmentFileName != null) { foreach (string Att in this.AttachmentFileName) { if (System.IO.File.Exists(Att)) { Mail.Attachments.Add(Att, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); } } }
          Mail.Display(false);
  
          try
          {
              Mail.Send();
          } catch (System.Exception ex) { throw ex; }
  
          /*
          while (!Mail.Sent &amp;&amp; Waited &lt; WaitingForSending)
          {
              System.Threading.Thread.Sleep(500);
              Waited += 0.5;
          }
          */
      }
  }
  </code></pre>
  
  <p>The "waiting loop", I commented is not working, because outlook is closing
  in the function <code>Mail.Send()</code>.</p>
  
  <p>Does anybody have an idea, how I can let outlook wait until the mail is sent?</p>
  
  <p>Greetings,
  Jan</p>