Previously we discussed how to send an Email using a Email Template, but we noticed it just sends the email but no chance of create and save as a draft. In some instances we need to create the Draft email to be sent later after checking or/and modifications by the user.
In such situations we can use below code. One can say its simply possible to use CREATE message of the Org service to achieve this but it is not possible to use a Template which is a constrain.
By creating the draft first, it allows you to programmatically or manually attach attachments prior to sending the email.
Here InstantiateTemplateRequest message does the magic.
public void CreateDraftEmailToPrimaryContactOfAccount(Account account) { InstantiateTemplateRequest request = new InstantiateTemplateRequest() { TemplateId = new Guid("bf0b97c7-d5a3-4a3f-8771-a1cd737ab555"), ObjectId = account.Id, ObjectType = Account.LogicalName }; InstantiateTemplateResponse response = (InstantiateTemplateResponse)OrgService.Execute(request); Entity email = response.EntityCollection[0]; Entity Fromparty = new Entity("activityparty"); Entity Toparty = new Entity("activityparty"); Toparty["partyid"] = new EntityReference(Account.EntityLogicalName, account.PrimaryContactId.Id); Fromparty["partyid"] = new EntityReference("queue", new Guid("f14a45e9-fac5-4ba0-9a95-c07fe1adabf0")); email["from"] = new Entity[] { Fromparty }; email["to"] = new Entity[] { Toparty }; email["directioncode"] = true; email["regardingobjectid"] = new EntityReference(Account.EntityLogicalName, account.Id); Guid emailId = OrgService.Create(email); }
When ready if you need to send the Email programmatically, below SendEmailRequest message can be used as below.
SendEmailRequest sendEmailRequest = new SendEmailRequest { EmailId = emailId, TrackingToken = string.Empty, IssueSend = true }; SendEmailResponse sendEmailResponse = (SendEmailResponse)OrgService.Execute(sendEmailRequest);
Related Posts
Programmatically send Email with Template (c#)