Saturday, August 10, 2019

How to send an email from Dynamic CRM in C#


private void SendEmail(IOrganizationService service, EntityReference sender, EntityReference recipientID, string subject, string body, bool hasCC, Guid cc, Entity regardingEntity)
{
    Guid _emailid = Guid.Empty;

    Entity FromParty = new Entity("activityparty");
    FromParty["partyid"] = new EntityReference(sender.LogicalName, sender.Id);

    Entity Email = new Entity("email");

    Entity ToParty = new Entity("activityparty");
    ToParty["partyid"] = new EntityReference(recipientID.LogicalName, recipientID.Id);

    Email.Attributes["to"] = new Entity[] { ToParty };

    if (hasCC)
    {
        Entity ccParty = new Entity("activityparty");
        ccParty["partyid"] = new EntityReference("systemuser", cc);
        Email.Attributes["cc"] = new Entity[] { ccParty };
    }

    Email.Attributes["from"] = new Entity[] { FromParty };
    Email.Attributes["subject"] = subject;
    Email.Attributes["description"] = body;

    Email.Attributes["regardingobjectid"] = new EntityReference(regardingEntity.LogicalName, regardingEntity.Id);
    _emailid = service.Create(Email);

    if (_emailid != Guid.Empty)
    {
        SendEmailRequest sendEmailreq = new SendEmailRequest
        {
            EmailId = _emailid,
            TrackingToken = "",
            IssueSend = true
        };

        SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
    }
}


Here are some points to notes:

FromParty / Sender

The sender could be SystemUser or Queue (Mailbox) only.



ToParty / Recipient

The most common external recipient is Account, Contact and Lead and internal being Users and Queues. 



No provision to send mail with importance or priority in Dynamic CRM
Dynamic CRM SDK do not provide any provision to mark email with high priority or importance which is there in outlook.

Email Created and Email Sent are two different action
As you might have noticed we have first created an email activity which is usually in Draft state and then further we need to create SendEmailRequest to send an email.

Template Content Change
We can send an email with email template as using Dynamic CRM SDK and can even change the template content dynamically.
Attachment
Dynamic CRM SDK also provide support to send an email along with attachments.


Regards,
Vipin Jaiswal

No comments: