Feb 14, 2025

Programmatically send Email with Template (c#)

This is a code snippet that sends Email programmatically (in C#) while using an Email Template

Explained scenario, we send an Email to Primary Contact of the Account. We set Account as the regarding object of the Email so this Email activity will associate with Account and will be displayed in Account's timeline. Also we have to pass Account as the regarding object of Template since we want dynamic fields of Template to be filled with Account field values as necessary.

Actually SendEmailFromTemplateRequest message does the magic.

public void SendEmailToPrimaryContactOfAccount(Account account)
{
    Entity Fromparty = new Entity("activityparty");
    Entity Toparty = new Entity("activityparty");
    Toparty["partyid"] = new EntityReference(Contact.EntityLogicalName, account.PrimaryContactId.Id);
    Fromparty["partyid"] = new EntityReference("queue", new Guid("f14a45e9-fac5-4ba0-9a95-c07fe1adabf0"));
    Entity email = new Entity("email");
    email["from"] = new Entity[] { Fromparty };
    email["to"] = new Entity[] { Toparty };
    email["directioncode"] = true;
    email["regardingobjectid"] = new EntityReference(Account.EntityLogicalName, account.Id);

    SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
    {
        Target = email,
        TemplateId = new Guid("bf0b97c7-d5a3-4a3f-8771-a1cd737ab555"),
        RegardingId = account.Id,
        RegardingType = Account.EntityLogicalName
    };
    var emailUsingTemplateRes = OrgService.Execute(emailUsingTemplateReq);
} 

Please note I am sending this email from a queue record. Obviously you can send from a system users as well. In such case, from activity party has to be changed accordingly.

One thing to note is, this method just sends the email, so you are not save Email in draft status.

Related Posts
Programmatically create a draft Email using Email Template (C#)

No comments:

Post a Comment