Search code examples
dynamics-crmmicrosoft-dynamicsemail-attachmentsdynamics-365

Dynamics CRM: How to create an email record with attachment using C#


I want to create an email record, and will it mark as 'Received', and may be added attachment to this new email record. Anybody know how to do that using C#?


Solution

  • There is an Official example code but no attachment included, so I will use my code here:

    There are three steps:

    1. Create an email record.
    2. Create attachment records for email.
    3. Send this email with SendEmailRequest

    Here is the sample code:

    // 1. Create the email record.
    Entity newEmail = new Entity("email");
    newEmail["subject"] = "your email subject";
    newEmail["description"] = "your email content";
    
    Entity toparty = new Entity("activityparty");
    toparty["addressused"] = "to@email.com";
    Guid contactid = new Guid();
    toparty["partyid"] = new EntityReference("contact", contactid);
    newEmail["to"] = new Entity[] { toparty };
    
    Entity fromparty = new Entity("activityparty");
    fromparty["addressused"] = "from@email.com";
    Guid userid = new Guid();
    fromparty["partyid"] = new EntityReference("systemuser", userid);
    newEmail["from"] = new Entity[] { fromparty };
    
    Guid targetEmailId = serviceproxy.Create(newEmail);
    
    // 2. Create Attachment for email
    Entity linkedAttachment = new Entity("activitymimeattachment");
    linkedAttachment.Attributes["objectid"] = new EntityReference("email", targetEmailId);
    linkedAttachment.Attributes["objecttypecode"] = "email";
    linkedAttachment.Attributes["filename"] = "DemoAttachment.pdf";
    linkedAttachment.Attributes["mimetype"] = "application/pdf";
    linkedAttachment.Attributes["body"] = "your attachment file stream in BASE64 format string";
    serviceproxy.Create(linkedAttachment);
    
    // 3. Send the email with SendEmailRequest method.
    SendEmailRequest sendEmailRequest = new SendEmailRequest
    {
        EmailId = targetEmailId,
        TrackingToken = "",
        IssueSend = true
    };
    SendEmailResponse sendEmailresp = (SendEmailResponse)serviceproxy.Execute(sendEmailRequest);
    

    More ref:

    activityparty is a special type, you can get more info here

    SendEmailRequest official document here