Skip to main content
Post a question

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Sending unique Email via Web API CRM

Like (0) ShareShare
ReportReport
Posted on 20 Nov 2017 09:36:37 by Microsoft Employee

Hi,

I'm building a subscription of new pages on a website. The visitors can post data via a form at the website with first- and lastname, E-mail and X.

Then they get inserted in different marketing lists based on value of X.

I'm able to get those contacts in the marketing lists from C# and the Web API with a token. I need to loop through all members in the marketing lists - get emailaddress and send them an email that now is a new page available at the website with this URL.

So i can't use a template i guess, i need it to be quite dynamic. Best case would be if i could use a template with unique parameters as link url, heading and text maybe. So the subscribers get an email when a new page is created on the website based on the value X.

How should i do this?

I checked the documentation of the Web API and it seems like i need to sent ID of template as a parameter for the methods SendEmailFromTemplate and SendTemplate? Do i first need to create a template, how can i map links, heading and body of the template with different values?

Br,

*This post is locked for comments

  • Verified answer
    Jlavos Profile Picture
    Jlavos 345 on 04 Dec 2017 at 02:35:43
    RE: Sending unique Email via Web API CRM

    Thank you, I was using "@odata.id" and should have been using the key name for the regarding the entity, as per below, this is now working fine.SendEmailFromTemplateWorking.png

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on 01 Dec 2017 at 06:37:39
    RE: Sending unique Email via Web API CRM

    Hi, yes. This should work:

    /api/data/v8.2/SendEmailFromTemplate

    Method: POST

    {

    "TemplateId": "439E68A8-74CF-E711-8121-E0071B658E81",

    "Regarding": { "contactid": "e01dc812-f2c5-e711-8119-e0071b66e2e1", "@odata.type": "Microsoft.Dynamics.CRM.contact" },

    "Target":  {

    "subject": "AEmail demo from Web API with Template",

    "description": "aThis is the description Template text",

    "regardingobjectid_contact@odata.bind": "/contacts(e01dc812-f2c5-e711-8119-e0071b66e2e1)",

        "email_activity_parties": [

           { "partyid_systemuser@odata.bind": "/systemusers(23bba18a-35c4-e211-411e-e0071b65be92)", "participationtypemask": 1 },

           { "partyid_contact@odata.bind": "/contacts(e01dc812-f2c5-e711-8119-e0071b66e2e1)", "participationtypemask": 2 }

         ],

         "@odata.type": "Microsoft.Dynamics.CRM.email"

    }

    }

    And getting this response (snippet of the whole response):

    {

       "@odata.context": "mycloudtest.api.crm4.dynamics.com/.../v8.2$metadata#emails/$entity",

       "@odata.etag": "W/\"6069300\"",

          ...............

    }

    An new email get sent to the contact. However the field "description" and "subject" from my post does not get used in the email. But the subject and description in the template instead. I tried with placeholders and so but with no luck.

    Now i'm creating my own template instead and then use SendEmail Action instead.

    /api/data/v8.2/emails

    Method: POST

    {

    "subject": "Email demo from Web API",

    "description": "This is the description text",

    "regardingobjectid_contact@odata.bind": "/contacts(e01dc812-f2c5-e711-8119-e0071b66e2e1)",

        "email_activity_parties": [

           { "partyid_systemuser@odata.bind": "/systemusers(23bba18a-35c4-e211-411e-e0071b65be92)", "participationtypemask": 1 },

           { "partyid_contact@odata.bind": "/contacts(e01dc812-f2c5-e711-8119-e0071b66e2e1)", "participationtypemask": 2 }

         ]

    }

    And then the ID for the new created email get used in the next Action, SendEmail.

    /api/data/v8.2/emails(insert-guid-of-created-email)/Microsoft.Dynamics.CRM.SendEmail

    Method: POST

    {  

    "IssueSend": true

    }

  • Jlavos Profile Picture
    Jlavos 345 on 01 Dec 2017 at 06:21:07
    RE: Sending unique Email via Web API CRM

    Where you able to solve this?

    I'm calling this aciton as :

    /api/data/v8.2/SendEmailFromTemplate

    {

    "TemplateId":"CD512306-14D6-E711-80CE-00155D016797",

    "Regarding":  

    {

    "@odata.type": "Microsoft.Dynamics.CRM.opportunity",

             "@odata.id": "e63d7331-8bcb-e711-80cd-00155d016797"            

    },

    "Target":

    {

    "@odata.type": "Microsoft.Dynamics.CRM.email",

              "@odata.id": "d34e3955-59d6-e711-80ce-00155d016797"  

       }

    }

    but getting the error below:

    {"error": {

      "code": "",

      "message": "Required field 'RegardingType' is missing",

      "innererror":    {

         "message": "Required field 'RegardingType' is missing",

         "type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",

         "stacktrace": "   at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Execute(OrganizationRequest request, ExecutionContext executionContext)\r\n   at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.ExecuteOperation(CrmODataExecutionContext context, EdmOperation edmOperation, Dictionary`2 parameters, Dictionary`2 boundParameters)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.ProcessOperationRequest(String operationName, Dictionary`2 operationParameters, EntityReference entityReference, String boundEntityName, String boundEntityType)\r\n   at Microsoft.Crm.Extensibility.OData.ActionController.PostUnboundAction(String operationName, ODataUntypedActionParameters parameters)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"

      }

    }}

    can't seem to be able to understand how to send RegardingType field

  • Community Member Profile Picture
    Community Member Microsoft Employee on 23 Nov 2017 at 14:10:47
    RE: Sending unique Email via Web API CRM

    I tried something like:

    {

    "TemplateId": "id-for-email-template",

    "Regarding": [ { "contactid@odata.bind": "/contacts(contact-guid-X)" } ],

    "Target": {

        "email_activity_parties": [

           { "partyid_systemuser@odata.bind": "/systemusers(systemuser-guid-Y)", "participationtypemask": 1 }, //1 is "sender"

           { "contactid@odata.bind": "/contacts(contact-guid-X)", "participationtypemask": 2 } // 2 is "to"

         ],

        "description": "description lorem ipsum",

        "subject": "rubrik",

        "contactid@odata.bind": "/contacts(contact-guid-X)"

       }

    }

    But i need to explicit set the type with @odata.type i guess.. hmm

  • Community Member Profile Picture
    Community Member Microsoft Employee on 23 Nov 2017 at 08:37:52
    RE: Sending unique Email via Web API CRM

    So i have created an email template at the CRM and it semse like the code finds it!

    This is the action i think i'm after: 

    https://msdn.microsoft.com/en-us/library/mt607523.aspx

    If i check the documentation at the SOAP Service there is actually examples: 

    https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.sendemailfromtemplaterequest.aspx?cs-save-lang=1&amp

    But i'm going with the Web API.

    So i tried this:

    1. dynamic regarding = new ExpandoObject();
    2.  
    3. var oppIndexer = regarding as IDictionary<string, Object>;
    4.  
    5. oppIndexer["contactid"] = contact.ContactId; //contact that will recive the
    6.  
    7. email.
    8.  
    9. oppIndexer["@odata.type"] = "Microsoft.Dynamics.CRM.contact";

    1. dynamic target = new ExpandoObject();
    2.  
    3. var targetIndexer = target as IDictionary<string, Object>;
    4.  
    5. targetIndexer["torecipients"] = "myemail@outlook.com";
    6.  
    7. targetIndexer["sender"] = "mysecondemail@businessname.com";
    8.  
    9. targetIndexer["inreplyto"] = "mysecondemail@businessname.com";
    10.  
    11. targetIndexer["subject"] = "This is the subject";
    12.  
    13. targetIndexer["description"] = "This should be the body of the email";
    14.  
    15. targetIndexer["directioncode"] = true; //outgoing
    16.  
    17. targetIndexer["@odata.type"] = "Microsoft.Dynamics.CRM.email";
    18.  
    19. dynamic sendEmailFromTemplate = new ExpandoObject();
    20.  
    21. sendEmailFromTemplate.TemplateId = Guid.Parse("my-email-template-guid-inserted-here");
    22.  
    23. sendEmailFromTemplate.Regarding = regarding;
    24.  
    25. sendEmailFromTemplate.Target = target;
    26.  
    27. api.ExecuteAction("SendEmailFromTemplate", sendEmailFromTemplate);


    But i get exception: "The e-mail must have at least one recipient before it can be sent" when i post it.

    What might be the problem?

    I think the documentation at: 

    https://msdn.microsoft.com/en-us/library/mt607523.aspx

    Just declare that the type for target and regarding should be of type "crmbaseentity". A base class...

    Anyone know what might cause this?

    This is the Email Entity: 

    https://msdn.microsoft.com/en-us/library/mt608007.aspx

    For the field "torecipients" one could read: "Shows the email addresses corresponding to the recipients". So i'm not sure this is the field i should use. If the text would be "The recipients with "," separator that will recive the message" i would be more certain that i would have to use this field.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Tip: Become a User Group leader!

Join the ranks of valued community UG leaders

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,305 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,084 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans
Loading complete