Ну, в конце концов, я понял это. Вот метод, который создаст почтовое сообщение, сохранит его как черновик, добавит вложение и отправит электронное письмо. Надеюсь, это поможет кому-то, кто не смог найти хороший пример, подобный мне.
В моем примере я буду отправлять файлы excel, поэтому тип контента установлен так, как он есть. Это можно, очевидно, изменить для поддержки любого типа прикрепления файла.
Для вашей справки переменная esb является переменной уровня класса типа 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);
}
Вы используете управляемый API или только EWS? Биты немного отличаются, но все еще довольно легко. Следуйте инструкциям, которые вы создали, чтобы создать экземпляр электронной почты, а затем в управляемом API все, что вам нужно сделать, это: email.Attachments.Add (имя_файла); – Chris
Я использую только EWS. Я нашел один пример, который создает FileAttachmentType, а затем создает CreateAttachmentType из этого файла. Затем он вызывает ews.CreateAttachment с помощью CreateAttachmentType. Это то, что я должен делать? Я надеялся, что это будет немного более интуитивно понятным, как подсказывает ваш ответ, но я обнаружил, что прикрепление файла к письму немного более «нечеткое», чем я ожидал. – Anthony