Вопрос

Я новый, чтобы использовать Повсеместливость (Exchange Web Service), и я ищу простой пример, который демонстрирует, как отправить электронное письмо с приложением. Я искал пример, и я не могу найти какие-то простые и четкие. Я нашел примеры о том, как отправить электронную почту, но не отправляя электронное письмо с приложением.

У кого-нибудь есть ссылка на пример, который они рекомендуют? Размещение примера здесь будет работать так же хорошо!

Это было полезно?

Решение

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

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

Для справки, переменная эс является переменной классов уровня Type ExchangeServiceBinding.

Редактировать

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

public void SendEmail(string from, string to, string subject, string body, byte[] attachmentAsBytes, string attachmentName)
        {
            //Create an email message and initialize it with the from address, to address, subject and the body of the email.
            MessageType email = new MessageType();

            email.ToRecipients = new EmailAddressType[1];
            email.ToRecipients[0] = new EmailAddressType();
            email.ToRecipients[0].EmailAddress = to;

            email.From = new SingleRecipientType();
            email.From.Item = new EmailAddressType();
            email.From.Item.EmailAddress = from;

            email.Subject = subject;

            email.Body = new BodyType();
            email.Body.BodyType1 = BodyTypeType.Text;
            email.Body.Value = body;

            //Save the created email to the drafts folder so that we can attach a file to it.
            CreateItemType emailToSave = new CreateItemType();
            emailToSave.Items = new NonEmptyArrayOfAllItemsType();
            emailToSave.Items.Items = new ItemType[1];
            emailToSave.Items.Items[0] = email;
            emailToSave.MessageDisposition = MessageDispositionType.SaveOnly;
            emailToSave.MessageDispositionSpecified = true;

            CreateItemResponseType response = esb.CreateItem(emailToSave);
            ResponseMessageType[] rmta = response.ResponseMessages.Items;
            ItemInfoResponseMessageType emailResponseMessage = (ItemInfoResponseMessageType)rmta[0];

            //Create the file attachment.
            FileAttachmentType fileAttachment = new FileAttachmentType();
            fileAttachment.Content = attachmentAsBytes;
            fileAttachment.Name = attachmentName;
            fileAttachment.ContentType = "application/ms-excel";

            CreateAttachmentType attachmentRequest = new CreateAttachmentType();
            attachmentRequest.Attachments = new AttachmentType[1];
            attachmentRequest.Attachments[0] = fileAttachment;
            attachmentRequest.ParentItemId = emailResponseMessage.Items.Items[0].ItemId;

            //Attach the file to the message.
            CreateAttachmentResponseType attachmentResponse = (CreateAttachmentResponseType)esb.CreateAttachment(attachmentRequest);
            AttachmentInfoResponseMessageType attachmentResponseMessage = (AttachmentInfoResponseMessageType)attachmentResponse.ResponseMessages.Items[0];

            //Create a new item id type using the change key and item id of the email message so that we know what email to send.
            ItemIdType attachmentItemId = new ItemIdType();
            attachmentItemId.ChangeKey = attachmentResponseMessage.Attachments[0].AttachmentId.RootItemChangeKey;
            attachmentItemId.Id = attachmentResponseMessage.Attachments[0].AttachmentId.RootItemId;

            //Send the email.
            SendItemType si = new SendItemType();
            si.ItemIds = new BaseItemIdType[1];
            si.SavedItemFolderId = new TargetFolderIdType();
            si.ItemIds[0] = attachmentItemId;
            DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
            siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
            si.SavedItemFolderId.Item = siSentItemsFolder;
            si.SaveItemToFolder = true;

            SendItemResponseType siSendItemResponse = esb.SendItem(si);
        }

Другие советы

Я знаю, этот вопрос очень старый, но я приземлился здесь после поиска Google. Вот обновленный упрощенный рабочий ответ с использованием утверждений.

Вам необходимо добавить пакет Nuget Microsoft.Exchange.Webservices к вашему проекту (текущая версия 2.2.0).

using Microsoft.Exchange.WebServices.Data;

namespace Exchange
{
    public static class Emailer
    {
        public static void SendEmail(string from, string to, string subject, string body, byte[] attachmentBytes, string attachmentName)
        {
            var service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            service.AutodiscoverUrl(from);
            var message = new EmailMessage(service)
            {
                Subject = subject,
                Body = body,
            };
            message.ToRecipients.Add(to);
            message.Attachments.AddFileAttachment(attachmentName, attachmentBytes);
            message.SendAndSaveCopy();
        }
    }
}

Призыв к Service.autoDiscoverURL может занять много секунд - если вы знаете URL-адрес, вы можете избежать вызова AutoDiscoverURL и настроить его напрямую. (Вы можете восстановить его один раз, позвонив AutodiscoverURL, затем печатать Service.url.)

// service.AutodiscoverUrl(from); // This can be slow
service.Url = new System.Uri("https://outlook.domain.com/ews/exchange.asmx");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top