2

Я вижу ошибки при экспорте электронной почты в офис 365, используя ews managed api, «Сервер не может обслуживать этот запрос прямо сейчас. Повторите попытку позже». Почему эта ошибка возникает и что можно сделать по этому поводу?EWS Сервер не может обслуживать этот запрос прямо сейчас

Я использую следующий код для этой работы: -

  _GetEmail = (EmailMessage)item; 
      bool isread = _GetEmail.IsRead; 
      sub = _GetEmail.Subject; 
      fold = folder.DisplayName; 
      historicalDate = _GetEmail.DateTimeSent.Subtract(folder.Service.TimeZone.GetUtcOffset(_GetEmail.DateTimeSent)); 
           props = new PropertySet(EmailMessageSchema.MimeContent); 
           var email = EmailMessage.Bind(_source, item.Id, props); 

           bytes = new byte[email.MimeContent.Content.Length]; 
           fs = new MemoryStream(bytes, 0, email.MimeContent.Content.Length, true); 
           fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); 

           Demail = new EmailMessage(_destination); 
           Demail.MimeContent = new MimeContent("UTF-8", bytes); 

           // 'SetExtendedProperty' used to maintain historical date of items 
           Demail.SetExtendedProperty(new ExtendedPropertyDefinition(57, MapiPropertyType.SystemTime), historicalDate); 
           // PR_MESSAGE_DELIVERY_TIME 
           Demail.SetExtendedProperty(new ExtendedPropertyDefinition(3590, MapiPropertyType.SystemTime), historicalDate); 
           if (isread == false) 
           { 
            Demail.IsRead = isread; 
           } 

           if (_source.RequestedServerVersion == flagVersion && _destination.RequestedServerVersion == flagVersion) 
           { 
            Demail.Flag = _GetEmail.Flag; 
           } 

           _lstdestmail.Add(Demail); 

           _objtask = new TaskStatu(); 
           _objtask.TaskId = _taskid; 
           _objtask.SubTaskId = subtaskid; 
           _objtask.FolderId = Convert.ToInt64(folderId); 
           _objtask.SourceItemId = Convert.ToString(_GetEmail.InternetMessageId.ToString()); 
           _objtask.DestinationEmail = Convert.ToString(_fromEmail); 
           _objtask.CreatedOn = DateTime.UtcNow; 
           _objtask.IsSubFolder = false; 
           _objtask.FolderName = fold; 
           _objdbcontext.TaskStatus.Add(_objtask); 
           try 
           { 
            if (counter == countGroup) 
            { 
             Demails = new EmailMessage(_destination); 
             Demails.Service.CreateItems(_lstdestmail, _destinationFolder.Id, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone); 
             _objdbcontext.SaveChanges(); 
             counter = 0; 
             _lstdestmail.Clear(); 
            } 
           } 

           catch (Exception ex) 
           { 
            ClouldErrorLog.CreateError(_taskid, subtaskid, ex.Message + GetLineNumber(ex, _taskid, subtaskid), CreateInnerException(sub, fold, historicalDate)); 
            counter = 0; 
            _lstdestmail.Clear(); 
            continue; 
           } 

Эта ошибка возникает только при попытке экспортировать в офисе 365 счетов и прекрасно работает в случае Outlook 2010, 2013, 2016 и т.д ..

+0

, где определяется _destination. – Seabizkit

+0

@Seabizkit Я определил назначение на глобальном уровне не на уровне функции –

ответ

0

Обычно это происходит в случае превышения дросселирования EWS в Exchange. Это объясняется в here.

Убедитесь, что вы уже знали, что правила регулирования и ваш код соответствуют им. Вы можете найти политики регулирования, используя Get-ThrottlingPolicy, если у вас есть сервер.

+0

Не могли бы вы объяснить, как можно регулировать политику регулирования с помощью ews в C#? –

0

Один из способов решения проблемы дросселирования, с которой вы столкнулись, - это реализовать подкачку, а не запрашивать все элементы за один раз. Вы можете обратиться к this link.

Например:

using Microsoft.Exchange.WebServices.Data; 

static void PageSearchItems(ExchangeService service, WellKnownFolderName folder) 
{ 
    int pageSize = 5; 
    int offset = 0; 

    // Request one more item than your actual pageSize. 
    // This will be used to detect a change to the result 
    // set while paging. 
    ItemView view = new ItemView(pageSize + 1, offset); 

    view.PropertySet = new PropertySet(ItemSchema.Subject); 
    view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); 
    view.Traversal = ItemTraversal.Shallow; 

    bool moreItems = true; 
    ItemId anchorId = null; 
    while (moreItems) 
    { 
     try 
     { 
      FindItemsResults<Item> results = service.FindItems(folder, view); 
      moreItems = results.MoreAvailable; 

      if (moreItems && anchorId != null) 
      { 
       // Check the first result to make sure it matches 
       // the last result (anchor) from the previous page. 
       // If it doesn't, that means that something was added 
       // or deleted since you started the search. 
       if (results.Items.First<Item>().Id != anchorId) 
       { 
        Console.WriteLine("The collection has changed while paging. Some results may be missed."); 
       } 
      } 

      if (moreItems) 
       view.Offset += pageSize; 

      anchorId = results.Items.Last<Item>().Id; 

      // Because you’re including an additional item on the end of your results 
      // as an anchor, you don't want to display it. 
      // Set the number to loop as the smaller value between 
      // the number of items in the collection and the page size. 
      int displayCount = results.Items.Count > pageSize ? pageSize : results.Items.Count; 

      for (int i = 0; i < displayCount; i++) 
      { 
       Item item = results.Items[i]; 

       Console.WriteLine("Subject: {0}", item.Subject); 
       Console.WriteLine("Id: {0}\n", item.Id.ToString()); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Exception while paging results: {0}", ex.Message); 
     } 
    } 
} 
Смежные вопросы