.NET Publicado por: 2

Os dejamos un script para crear un mail en Dynamics a través del SDK con C#, añadirle algunos adjuntos, y enviarlo.

El material encontrado en Internet al respecto es bastante confuso, así que, tal vez os sirva esta versión.

Os pongo el código y luego os comento un poco…

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using AP.Crm;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;

namespace OneShotScripts.Commands
{
    public class SendEmailWithAttachmentsCommand
    {
        public CrmService _crmService = new CrmService();

        private const int NUMBER_POTENTIAL_HOUSES = 100000;

        public SendEmailWithAttachmentsCommand()
        {
            _crmService.ConfigureOrgService();
        }

        public void Execute()
        {
            var crmEmail = BuildMockMainEmail();
            var newId = _crmService.OrgServiceStatic.Create(crmEmail);

            // Email stored
            var files = BuildMockFiles();

            if (files.Count > 0)
            {
                foreach (var file in files)
                {
                    var attachment = new ActivityMimeAttachment
                    {

                        ObjectId = new EntityReference(Email.EntityLogicalName, newId),
                        ObjectTypeCode = Email.EntityLogicalName,
                        FileName = file.FileName,
                        Body = file.GetBase64(),
                    };

                    _crmService.OrgServiceStatic.Create(attachment);
                }
            }

            var sendEmailreq = new SendEmailRequest
            {
                EmailId = newId,
                TrackingToken = "",
                IssueSend = true
            };

            _crmService.OrgServiceStatic.Execute(sendEmailreq);
        }

        private List<FileItem> BuildMockFiles()
        {
            var mockedFiles = new List<FileItem>();
            mockedFiles.Add(new FileItem { FileName = "file_1.jpg", Content = new MemoryStream() });
            mockedFiles.Add(new FileItem { FileName = "file_2.jpg", Content = new MemoryStream() });
            return mockedFiles;
        }

        private List<FileItem> GetFilesFromRequest()
        {
            var files = new List<FileItem>();
            foreach (string file in HttpContext.Current.Request.Files)
            {
                var postedFile = HttpContext.Current.Request.Files[file];
                var memStream = new MemoryStream();
                postedFile.InputStream.CopyTo(memStream);
                files.Add(new FileItem { FileName = postedFile.FileName, Content = memStream });
            }
            return files;
        }

        public Email BuildMockMainEmail()
        {
            const string EMAIL_FROM_GUID = "0000-0000-0000-0000-0000-0000";
            const string EMAIL_TO_GUID = "0000-0000-0000-0000-0000-0000";
            const string EMAIL_OWNER_GUID = "0000-0000-0000-0000-0000-0000";
            const string EMAIL_REGARDING_GUID = "0000-0000-0000-0000-0000-0000";
            const string EMAIL_REGARDING_ENTITY = "Contact";
            const string EMAIL_SUBJECT = "Email subject";
            const string EMAIL_BODY = "Email description";

            var fromEntity = new ActivityParty
            {
                PartyId = new EntityReference(SystemUser.EntityLogicalName, new Guid(EMAIL_FROM_GUID))
            };

            var toEntity = new ActivityParty
            {
                PartyId = new EntityReference(Lead.EntityLogicalName, new Guid(EMAIL_TO_GUID))
            };

            var crmEmail = new Email
            {
                Subject = EMAIL_SUBJECT,
                Description = EMAIL_BODY,
                From = new ActivityParty[] { fromEntity },
                To = new ActivityParty[] { toEntity },
                OwnerId = new EntityReference(SystemUser.EntityLogicalName, new Guid(EMAIL_OWNER_GUID)),
                RegardingObjectId = new EntityReference(EMAIL_REGARDING_ENTITY, new Guid(EMAIL_REGARDING_GUID)),
                ScheduledEnd = DateTime.Now,
                StateCode = EmailState.Completed
            };

            return crmEmail;
        }


        public class FileItem
        {
            public string FileName { get; set; }
            public MemoryStream Content { get; set; }

            public string GetBase64()
            {
                return Convert.ToBase64String(this.Content.GetBuffer());
            }
        }
    }
}

Pues bien. El código básicamente consiste en una clase ‘command’ (métodos que hace nosas y no devuelven nada), la cual al instanciarse configura nuestra clase de servicio que conecta con el CRM (Esto os lo dejamos a vosotros), y luego tiene un método público «Execute» que es el que hace el trabajo.

Veréis que básicamente construye un mail, crea unos ‘fakes’ o ‘mocks’ de los ficheros y los crea como adjuntos asociados, y luego hace la llamada para que se envíe el mail.

Puntos a comentar:

Primero creamos el mail y luego le añadimos los adjuntos ya que necesitamos el ID del mail generado para poder crear los adjuntos.

Nos apoyamos en una clase «File item» para tener los nombres de los ficheros y su contenido. El contenido lo guardamos como un MemoryStream ya que es compatible con la forma con la que obtenemos el contenido de la Request si queremos cogerlo de ahí. (Podríamos cambiar la línea «var files = BuildMockFiles();» por «var files = GetFilesFromRequest();» para ver como sería esto).

En este caso hemos decidido por simplicidad que esté todo junto. Lo suyo sería segregar las responsibilidades y demás, y tal vez no dejar la generación del base64 al propio FileItem, pero bueno, eso ya os lo dejamos como ejercicio de refactoring para que lo adaptéis a vuestro gusto.

Breve explicación en inglés por si alguien lo busca en este idioma.

English sum up:

This post talks about how to create and send a new Email activity with attachments into Dynamics CRM throw the SDK with C#.

The main idea is you have to create the email so you have the ID to create the attachments and then once everything is done we can send the email.

Just to point out we leave the method »
GetFilesFromRequest» to ilustrate how to get the files from the request in case you need it.

For more details, just google translate the content of the post in Spanish.

Happy coding!

2 Comentarios

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.