Tuesday 4 November 2014

Dynamically change the user email address when sending emails

When you need that several users use the same email address when sending emails, you can do this with creating a queue, setting the email configuration to that queue and every time an user need to send an email, he can change on the "from" field to the queue.

The problem is sometimes the user forgot to change address and the email is send with the wrong email address or not send at all (the user don't have mailbox configured)

This is a solution to dynamaclly change the email address to the default queue of the user every time you create a new email or reply to an email.

Note: This will change every user to the his default queue.

- Change the default queue of every user to the some default queue.
- Configure and test email sending through this queue.

Now the code:

Need to create 2 JavaScript web resources

new_REST_SDK: You can find the SDK.REST.js on CRM 2011/2013 SDK in SDK\SampleCode\JS\RESTEndpoint\JavaScriptRESTRetrieveMultiple\JavaScriptRESTRetrieveMultiple\Scripts

Use the this code on the web resource text editor

function GetDefaultQueue() {  
   if (Xrm.Page.ui.getFormType() === 1 || Xrm.Page.ui.getFormType() === 2) // new form or update form  
   {  
     //Get GUID of logged user  
     var userId = Xrm.Page.context.getUserId();  
     SDK.REST.retrieveMultipleRecords("SystemUser", "$select=QueueId&$filter=SystemUserId eq guid'" + userId + "'",  
     function (results) {  
       var firstResult = results[0];  
       if (firstResult !== null) {  
         var queueId = results[0].QueueId.Id;  
         var queueName = results[0].QueueId.Name;  
         }  
       var lookup = new Array();  
       var lookupItem = new Object();  
       lookupItem.id = queueId;  
       lookupItem.name = queueName;  
       lookupItem.typename = "queue";  
       lookup[0] = lookupItem;  
       Xrm.Page.getAttribute("from").setValue(lookup);  
     }, function(){}, function(){})   
     function errorHandler(error) {  
       alert(error.message);  
     }  
   }  
 }  

-         Save and publish.

-         After the web resources are inserted, go the email form editor and click in “Form Properties”.

-         Add to the form libraries the 2 web resources you created.




-         On the event handler choose (control: form and event: OnLoad)

-         Click on add and use this parameters




-         Save, close and publish.

Now when you try to send an email with one of the user with will change to the default queue.


No comments:

Post a Comment