MailItem.get_Recipients

ram27
ram27 used Ask the Experts™
on
Here is my platform:
 .net framewrok 1.1
 Windows Xp Propfessional
 MS Office 2007.
Visual Studio 2003.
Window based application.


I did below mentioned steps:
1. Right click on  C# projeect, select "Add Referece"
2. Go to "COM" tab
3. Select "MS Office 12.0 Object Library" and "Microsoft Outlook 12.0 Object Library" and click on "OK".
4. i have added below code.
using Outlook=Microsoft.Office.Interop.Outlook;


pls see code below


public static void SendMail(string[] MailTo, string MailSubject, string MailBody, bool OpenEmailEditor,params string[] attachmentSource)

            {                        

                  bool bResolve ;                  

                  string EmailDomain;      

                  int position;

                  int attachType;

                  string displayName;

                  FileInfo fi;

                  EmailDomain = "@" + MyConfig.Get("EMail","Domain");

                              Outlook.Recipient oRecipient;            

                  Outlook.ApplicationClass myOutlook = new Outlook.ApplicationClass();

                  Outlook.MailItem newMail = (Outlook.MailItem)myOutlook.CreateItem(Outlook.OlItemType.olMailItem);            

                  //Extract each recipient from Mailto and resolve them if they are valid id's

                  foreach (string s in MailTo)

                  {

                        if (s.Trim() != "")

                        {

                              if(s.IndexOf("@")== -1)

                              {

                                    string str="";

                                    str = s + EmailDomain;

                                    oRecipient = newMail.Recipients.Add(str);

                              }

                              else

                              {

                                    oRecipient = newMail.Recipients.Add(s); /* getting error */                         

                              }

                              

                              bResolve = oRecipient.Resolve();

                              if (!bResolve || oRecipient.Name.EndsWith(EmailDomain))

                              {                                    

                                    if (OpenEmailEditor == false)

                                    {                                          

                                          throw new MySystemException(ConstFrameworkError.ERRCD_INVALID_EMAIL_ID,new object[] {"",""});                                    

                                    }

                                    else

                                    {                                    

                                          newMail.Recipients.Remove(newMail.Recipients.Count);

                                          newMail.Recipients.Add(s);

                                    }      

                              }                              

                        }                        

                  }            

                  if(MailSubject != null)

                  {

                        newMail.Subject = MailSubject;

                  }

                  else

                  {

                        newMail.Subject = "";

                  }

                  if(MailBody != null)

                  {

                        newMail.Body = MailBody;

                  }

                  else

                  {

                        newMail.Body = "";

                  }

            position = (int)MailBody.Length + 1;//Position of the attachment in the outlook editor.                  

                  attachType = (int)Outlook.OlAttachmentType.olByValue;      

                  //Add all the attachments to new mail.

                  foreach(string path in attachmentSource)

                  {

                        //Add the attachment if file is present in the specified path.

                        if (File.Exists(path))                        

                        {

                              fi = new FileInfo(path);

                    displayName = fi.Name ;                                          

                              newMail.Attachments.Add(path,attachType,position,displayName);

                        }

                  }

                  if (OpenEmailEditor == true)                        

                  {                        

                        newMail.Display(true);

                  }

                  else

                  {      

                              

                              newMail.Send();                                                

                                                }      

                  oRecipient = null;

                  newMail = null;

                  myOutlook = null;                  



            }

 above mentioned function can be called in  two ways.
First one see below code:
Here outlook editior will be opned when below code is executed and user will type to address and he will click "send" button on the outlook editor

string[]      toAddress = new string[1];

string subject="test subject";

string messageBody ="test message body";

toAddress[0]= "";



SendMail(toAddress,      subject,messageBody,true);

Second way:
in this case, outlook editor will not open and email will be sent to "toaddress" email automatically and will display message box saying that "email has been sent" etc.

string[] mailTo = new string[1];

string subject;

string mailBody;

string[] attachment = new string[1];



mailTo[0] = "mytestemail@xyz.com";

mailBody = "my test body";

subject="test subject";

attachment[0] = "c:\\myfile.xlsx";

SendMail(mailTo,subject,mailBody,false,attachment);<br/>MessageBox.Show("email sent sucessfully");

                                                

Both the ways it works when outlook instace is opened on the machine where i am testing.
When "outlook instace" is not opened, first way still works no problems. But when i call second way am getting an exception "UnHandled Exception,999,Operation aborted,Microsoft.Office.Interop.Outlook._MailItem.get_Recipients()".

If outlook instace is opened i did not encounter any errors but when out look is not opened at that when am testing above second way( i..e, SendMail(mailTo,subject,mailBody,false,attachment);), i am getting error. please help.
Please let me know what is the problem.
Thanks,

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Miguel OzSenior Software Engineer
Top Expert 2009

Commented:
If your objective is to send email only. I will suggest using SMTP using .net 1.1.
http://www.codeproject.com/KB/cs/Sending_Mails_From_C_.aspx

I think your problem is that you are creating an Outlook application every time you send mail (I will make it a field for the lifetime of your form depending on usage) and this object is not being proerly released. If you do operations multiple times it will kill Outlook because Outlook works in a STA thread COM model.

Thus, as a first improvement, you need to release the com objects, before setting to null and force Garbage collection.
Marshal.ReleaseComObject(oRecipient);
Marshal.ReleaseComObject(newMail);
Marshal.ReleaseComObject(myOutlook);
oRecipient = null;
newMail = null;
myOutlook = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Commented:
The reason for that is :
                                  "Outlook.MailItem.Recipients.Add(“emailId”)"  gives crash when outlook        instance is not opened on the machine which has Office 2007.
Solution:
Instead of using “Outlook.MailItem.Recipients” to use “Outlook.MailItem.To” i..e, Outlook.MailItem.To =”emailed”.
if use above solution, it is working fine without giving any errors.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial