简体   繁体   中英

Exchange Web Service raising exception: You must load or assign this property before you can read its value; When sending an email

Currently am implementing the code for sending a reply email using the Exchange Web service and C#. While debugging the same I come across this exception.

#Exception


Microsoft.Exchange.WebServices.Data.ServiceObjectPropertyException
  HResult=0x80131500
  Message=You must load or assign this property before you can read its value.
  Source=Microsoft.Exchange.WebServices
  StackTrace:
   at Microsoft.Exchange.WebServices.Data.PropertyBag.get_Item(PropertyDefinition propertyDefinition)
   at Microsoft.Exchange.WebServices.Data.Item.get_Body()
   at DataLoadLibrary.DataLoad.Email.TestPortRequestOauthBased.startDataload() in C:\Users\aadityaradhakrishnan\Development\IPACT\ROB\ipact-rob\DataLoadLibrary\DataLoad\Email\TestPortRequestOauthBased.cs:line 113
   at TestPortEmailReader.Program.<Main>d__8.MoveNext() in C:\Path\TestPortEmailReader\Program.cs:line 87

  This exception was originally thrown at this call stack:
    [External Code]
    DataLoadLibrary.DataLoad.Email.TestPortRequestOauthBased.startDataload() in TestPortRequestOauthBased.cs
    TestPortEmailReader.Program.Main(string[]) in Program.cs

#Implementation

public bool genericEmail(
                                string recepient,
                                string subject,
                                string bodyMessage,
                                Dictionary<string, string> replacementStrings = null,
                                string cc = "",
                                string bcc = "",
                                string headerMessage = "",
                                string footerMessage = "",
                                FileInfo[] attachments = null,
                                string[] filenames = null,
                                EmailMessage originalEmail = null,
                                ExchangeService exchangeClient = null)
        {

            EmailMessage email = new EmailMessage(exchangeClient);
            email.Sender.Address= config.exchangeUsername + "@domain.com";
            email.Sender.Name = "ABC";
            if (recepient.Length == 0) {
                email.ToRecipients.Add(ABCTeamEmail);
            }
            else
            {
                email.ToRecipients.Add(recepient.TrimEnd(';'));
            }
            if (cc.Length != 0)
                email.CcRecipients.Add(cc.TrimEnd(';'));
            if (config.environment != "PR")
            {
                email.Sender.Address = config.exchangeUsername + "@domain.com";
                email.CcRecipients.Add(null); 
            }

            if (attachments != null)
            {
                int i = 0;
                foreach (FileInfo fi in attachments)
                {
                    FileStream theStream = new FileStream(fi.FullName, FileMode.OpenOrCreate);
                    if (filenames == null)
                        email.Attachments.AddFileAttachment(fi.Name, theStream);
                    else
                        email.Attachments.AddFileAttachment(filenames[i], theStream);
                    i++;
                }
            }

            if (originalEmail != null)
            {
                string originalEmailFilename = config.extractFolder + "\\Emails" + originalEmail.Subject.Trim().Replace('\\', '_').Replace('/', '_').Replace(":", "_").Replace("\"", "_").Replace("*", "_").Replace("?", "_").Replace("<", "_").Replace(">", "_").Replace("|", "_") + "_" + originalEmail.DateTimeReceived.ToString("yyyyMMdd_HHmmss") + ".msg";
                originalEmail.Save(originalEmailFilename);
                email.Attachments.AddFileAttachment(originalEmailFilename);
                
            }

            if (config.environment == "PR")
                email.Subject = subject.Trim();
            else
                email.Subject = "[" + config.environment + "] " + subject.Trim();

            if (replacementStrings != null)
            {
                foreach (KeyValuePair<string, string> kv in replacementStrings)
                {
                    bodyMessage = bodyMessage.Replace(kv.Key, kv.Value);
                }
            }

            bodyMessage = bodyMessage.Replace("{headerMessage}", headerMessage);
            bodyMessage = bodyMessage.Replace("{footerMessage}", footerMessage);
            email.Body = new MessageBody(bodyMessage);
            email.Send();
                return true;
        }
    }

ews_oauth_adapter.genericEmail(respondTo, "RE: " + msgDetail.Subject.ToString() + " Incorrect Physical Name", physcalNameErrorMessage + BottomOfEmail + "<br><br><hr><br>" + msgDetail.Body, null, cc, "", "", "", null, null, null, exchclient);

**Getting the exception when calling the function genericEmail **

Not able to identify precisely what is wrong with my implementation. Went through some similar issues like Error while sending Email :you must load or assign this property before you can read its value -EWS . But couldn't find the same issue in my implementation.

#UPDATE

 try
                {
                    inbox_mails = tokenProvider.ReadEmailFromFolder(-5, 50, Inbox_ID.Id);
                    foreach (Item mailItem in inbox_mails)
                    {

                        EmailMessage mes = (EmailMessage)mailItem;
                        Console.WriteLine("\nRunning message: " + mailItem.Subject.ToString() + " From: " + mes.From.ToString());
                        logger.log("\nRunning message: " + mailItem.Subject.ToString() + " From: " + mes.From.ToString());
                        Console.WriteLine(mes.Body); // Showing the exception when trying to print the Mail Body.


                        //TestPortRequestOauthBased dataloader = new TestPortRequestOauthBased(config, logger, dbCommands, exchClient, mailItem);
                       

                    }

                        Thread.Sleep(sleepInterval);
                }
                catch(Exception e)
                {
                    Console.WriteLine("The operation timed out!! ");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    //ews_oauth_adapter.genericEmail(cc, "FATAL ERROR: Integration TestPort System", "System has crashed and needs to be restarted <br><br>" + e.Message + "<br>" + e.StackTrace, null, "", null, "", "", null, null, null);
                    throw e;
                }

 public FindItemsResults<Item> ReadEmailFromFolder(int mailSince, int mailLimt,  FolderId folder_id)
        {
            TimeSpan ts = new TimeSpan(mailSince, 0, 0, 0);
            DateTime date = DateTime.Now.Add(ts);
            SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
            var findResults = exchangeService.FindItems(folder_id, filter, new ItemView(mailLimt));
            return findResults;
        }

That error is telling you your trying to load a property you never requested from EWS. When you call that function you have

msgDetail.Body

Where is the code you get msgDetail from it most likely you haven't ever requested to return the body of the message in this code and it isn't returned by default in FindItems so with msgDeail there should have been a load at some point

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM