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.
Here is my code:
public class MyMail
{
private const double WaitingForSending = 30.0;
#region Local variables
public bool SSL_Encryption = true;
public System.Collections.Generic.List<System.Net.Mail.MailAddress> Address = null;
public System.Collections.Generic.List<System.Net.Mail.MailAddress> CC = null;
public System.Collections.Generic.List<System.Net.Mail.MailAddress> BCC = null;
public System.Collections.Generic.List<string> 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 && Waited < WaitingForSending)
{
System.Threading.Thread.Sleep(500);
Waited += 0.5;
}
*/
}
}
The "waiting loop", I commented is not working, because outlook is closing
in the function Mail.Send()
.
Does anybody have an idea, how I can let outlook wait until the mail is sent?
Greetings, Jan