Как загрузить почтовое вложение с помощью EWS в Exchange

Я использую ASP.Net MVC.

using (ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding())
{
    ICredentials creds = new NetworkCredential("username", "password");
    exchangeServer.Credentials = creds;
    exchangeServer.Url = "https://myexchangeserver.com/EWS/Exchange.asmx";

    FindItemType findItemRequest = new FindItemType();
    findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

    // define which item properties are returned in the response
    ItemResponseShapeType itemProperties = new ItemResponseShapeType();
    itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
    findItemRequest.ItemShape = itemProperties;

    // identify which folder to search
    DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
    folderIDArray[0] = new DistinguishedFolderIdType();
    folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

    // add folders to request
    findItemRequest.ParentFolderIds = folderIDArray;

    // find the messages
    FindItemResponseType findItemResponse = exchangeServer.FindItem(findItemRequest);

    // read returned
    FindItemResponseMessageType folder = (FindItemResponseMessageType)findItemResponse.ResponseMessages.Items[0];
    ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
    folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
    ItemType[] items = folderContents.Items;

    // if no messages were found, then return null -- we're done
    if (items == null || items.Count() <= 0)
    { return null; }


    // FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
    BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
    for (int i = 0; i < items.Count(); i++)
    {
        itemIds[i] = items[i].ItemId;
    }


    GetItemType getItemType = new GetItemType();
    getItemType.ItemIds = itemIds;
    getItemType.ItemShape = new ItemResponseShapeType();
    getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
    getItemType.ItemShape.BodyType = BodyTypeResponseType.HTML;
    getItemType.ItemShape.BodyTypeSpecified = true;

    GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemType);
    ItemType[] messages = new ItemType[getItemResponse.ResponseMessages.Items.Count()];
    List<MailRecipientModel> model = new List<MailRecipientModel>();
    for (int j = 0; j < messages.Count(); j++)
    {
        messages[j] = ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[j]).Items.Items[0];
        MailRecipientModel model1 = new MailRecipientModel();

        model1.Subject = messages[j].Subject;
        model1.FromAddress = messages[j].Sender.Item.EmailAddress;
        model1.DisplayName = messages[j].Sender.Item.Name;
        model1.Date = messages[j].DateTimeReceived.Date.ToString();
        model1.MailBody = messages[j].Body.Value;
        model1.MsgId = messages[j].ItemId.Id;
        if (messages[j].Attachments != null) {
            //
        }
        model.Add(model1);
    }              

    return model;
}

Этот мой код. Я хочу загрузить вложенный файл, и если вложенный файл является изображением, его отображают в браузере.

Я использую Microsoft ActiveSync Exchange Server.

Если вы знаете, как это сделать, пожалуйста, помогите мне.


person jayrag pareek    schedule 02.11.2016    source источник


Ответы (1)


Вы должны использовать операцию GetAttachment https://msdn.microsoft.com/en-us/library/office/aa494316(v=exchg.150).aspx . Пример прокси-кода https://blogs.msdn.microsoft.com/vikas/2007/10/15/howto-ews-use-getattachment-to-download-attachments-off-mailappointment/

person Glen Scales    schedule 03.11.2016
comment
Я не хочу загружать файлы вложений на свой сервер. Я просто хочу дать прямую ссылку для скачивания по почте. Является ли это возможным? - person jayrag pareek; 03.11.2016
comment
Не напрямую, а просто создайте конечную точку, на которую вы можете отправить AttachmentId, а затем обработайте AttachmentId на сервере с помощью EWS и отправьте содержимое обратно в браузер. В конце концов, ваш код должен быть аутентифицирован для доступа к любому вложению. Вызов API для доступа к любому вложению с помощью EWS — это операция GetAttachment, для которой вам нужен AttachmentId. - person Glen Scales; 03.11.2016
comment
у вас есть пример? - person jayrag pareek; 03.11.2016
comment
В ссылке, которую я разместил, есть пример использования GetAttachment в EWS. Создать что-то для отправки AttachmentId в ASP.Net MVC должно быть довольно просто. Вы должны попытаться сделать это самостоятельно, а затем задать вопрос о том, что вы не понимаете. - person Glen Scales; 03.11.2016
comment
Вы не можете сделать это с помощью EWS, MSG - это файл Outlook или, точнее, составной формат OLE. Не существует простого способа работы с этими файлами вне Outlook msdn.microsoft.com/en-us/library/office/. Вы можете сохранить сообщение в формате EML, используя EWS и MimeStream, но это не то же самое, что MSG, и не поддерживает точность элемента, такого же, как MSG, но для большинства случаев его использования вполне нормально. - person Glen Scales; 06.11.2016