Friday, 9 November 2012

Plugin - How to send an Email

Plugin's are very useful business process components within CRM, they can be attached and configured to execute based on certain events and execute pre-defined business logic.

How to send an Email from a plugin is today's post, code example:
private void SendEmail(IOrganizationService service,
    Guid recieverUserId,
    Guid senderUserId,
    Guid regardingObjectId,
    string emailBody,
    string emailSubject)
    Entity email = new Entity();
    email.LogicalName = "email";

    //Regarding field, the record, which you want this email associated to
    EntityReference regardingObject = new EntityReference("opportunity", regardingObjectId);

    //Define the Sender and Receiver
    EntityReference from = new EntityReference("systemuser", senderUserId);
    EntityReference to = new EntityReference("systemuser", recieverUserId);

    //Activity Party - From
    Entity fromParty = new Entity("activityparty");

    //Activity Party - To
    Entity toParty = new Entity("activityparty");
    toParty.Attributes.Add("partyid", to);

    EntityCollection collFromParty = new EntityCollection();
    collFromParty.EntityName = "systemuser";

    EntityCollection collToParty = new EntityCollection();
    collToParty.EntityName = "systemuser";

    email.Attributes.Add("to", collToParty);

    //Set Email Subject & Body
    email.Attributes.Add("description", emailBody);

    //Create email activity
    Guid emailID = service.Create(email);

    //Sending email
    SendEmailRequest reqSendEmail = new SendEmailRequest();
    reqSendEmail.EmailId = emailID;
    reqSendEmail.TrackingToken = string.Empty;
    reqSendEmail.IssueSend = true;           

    SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);

The method demonstrates how to send an email, passing in the appropriate parameters. This example is sending an email from and to internal System Users, however this can be easily adapted for other purposes.

Note: Your email mechanism need's to be configured correctly in order for this to work e.g. CRM Email Router. 

No comments:

Post a Comment

Action Microsoft.Crm.Setup.Common.Analyzer +CollectAction failed. Fatal error during installation

When installing the Srs Data Connection (Microsoft Dynamics CRM Reporting Extensions), you may have experienced the following error: ...