2010-09-29 9 views
8

Soy nuevo en el uso de EWS (Servicio web de Exchange) y estoy buscando un ejemplo simple que demuestre cómo enviar un correo electrónico con un archivo adjunto. He buscado un ejemplo y no puedo encontrar ninguno que sea simple y claro. He encontrado ejemplos sobre cómo enviar un correo electrónico pero no enviar un correo electrónico con un archivo adjunto.Servicios web de Exchange - Enviar correo electrónico con el archivo adjunto

¿Alguien tiene un enlace a un ejemplo que recomendaría? ¡Publicar un ejemplo aquí funcionaría igual de bien!

+0

¿Está utilizando la API administrada o simplemente EWS? Los bits varían ligeramente, pero siguen siendo bastante fáciles. Siga el tutorial que encontró para crear una instancia de correo electrónico y luego, en Managed API, todo lo que necesita hacer es: email.Attachments.Add (fileName); – Chris

+0

Estoy usando solo EWS. Encontré un ejemplo que crea un FileAttachmentType y luego crea un CreateAttachmentType a partir de ese archivo adjunto. Luego llama a ews.CreateAttachment utilizando CreateAttachmentType. ¿Es eso lo que debería estar haciendo? Esperaba que fuera un poco más intuitivo, como sugiere tu respuesta, pero descubro que adjuntar un archivo a un correo electrónico es un poco más "confuso" de lo que esperaba. – Anthony

Respuesta

9

Bueno, finalmente me di cuenta de esto. Aquí hay un método que creará un mensaje de correo electrónico, lo almacenará como borrador, agregará el archivo adjunto y luego enviará el correo electrónico. Espero que esto ayude a alguien que no fue capaz de encontrar un buen ejemplo como yo.

En mi ejemplo, solo enviaré archivos de Excel, razón por la cual el tipo de contenido se establece como está. Esto, obviamente, se puede cambiar para admitir cualquier tipo de archivo adjunto.

Para su referencia, la variable esb es una variable de nivel de clase de tipo ExchangeServiceBinding.

Editar

También debo señalar que, en este ejemplo, no estoy comprobando los tipos de respuesta de las acciones de intercambio para el éxito o el fracaso. Esto definitivamente debe verificarse si le interesa saber si sus llamadas a EWS funcionaron o no.

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); 
     } 
+0

¿Puedes mostrarnos tus importaciones por favor? –

3

Sé que esta pregunta es muy antigua, pero llegué aquí después de buscar en Google. Aquí hay una respuesta de trabajo simplificada actualizada con el uso de declaraciones.

Necesita agregar el paquete nuget Microsoft.Exchange.WebServices a su proyecto (la versión actual es 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(); 
     } 
    } 
} 

La llamada a service.AutodiscoverUrl puede tomar muchos segundos - si conoce la URL a continuación, puede evitar llamar AutodiscoverUrl y configurarlo directamente. (Puede recuperarlo una vez llamando a AutodiscoverUrl y luego a imprimir service.Url)

// service.AutodiscoverUrl(from); // This can be slow 
service.Url = new System.Uri("https://outlook.domain.com/ews/exchange.asmx"); 
Cuestiones relacionadas