CRM Crate

How to create an email activity in Microsoft CRM using PowerShell?

We will learn how to create an email in Microsoft CRM using PowerShell script. Before we start make sure you have gone through the below articles which covers what is Powershell and how to connect to Microsoft CRM using PowerShell.

In the below scenario we will trigger the email to a particular User B from a particular User A when the Account record’s field “Account Number” equals to value 1000.

Check Folder Size using PowerShell command - MSNoob

Below are the code highlights.

  • Defining .NET and SDK assemblies path.
  • Creating S2S service for CRM connection.
  • Using Fetch XML for retrieving Account records with Account Number equals “1000”.
  • Creating & sending an Email Activity request using CRM out of the box email functionality.

Below is the PowerShell script code.

#Initializing Assemblies.
$scriptDir =  Split-Path $script:MyInvocation.MyCommand.Path
Write-Host "Current script directory is $scriptDir"
Add-Type -Path "$scriptDir\Microsoft.IdentityModel.Clients.ActiveDirectory.dll";
Add-Type -Path "$scriptDir\Microsoft.Xrm.Sdk.dll"
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.IO")).Location;
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.Net")).Location;
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.Threading.Tasks")).Location;
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.Security")).Location;
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.Text.Encoding")).Location;
Add-Type -Path ([Reflection.Assembly]::LoadWithPartialName("System.Text.Encoding")).Location;

#Process Configuration.
$crmInstance = "https://crmcrate.crm.dynamics.com";
$crmClientId = "YOUR CLIENT ID";
$crmClientSecret = "YOUR SECRET ID";
      
#Initiliazing CRM S2S Service Proxy.
function GetS2SService()
{
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
    $clientcred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential -ArgumentList ($CrmClientId, $CrmClientSecret);
    $authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext -ArgumentList ("https://login.microsoftonline.com/dr36214hc-fre7-d567-c0y2-222f6fd0g30c");
    $authenticationContext.TokenCache.Clear();
    $authenticationResult = $authenticationContext.AcquireTokenAsync($CrmInstance, $clientcred).Result;
    $urlXRMSDK = New-Object System.Uri -ArgumentList ("$CrmInstance/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2");
    $_service = New-Object Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient -ArgumentList ($urlXRMSDK, [System.TimeSpan]::MaxValue , $false);
    $_service.HeaderToken = $authenticationResult.AccessToken;
    return $_service;
}

#Initializing Web Proxy.
function GetS2SServiceOrgWebProxy()
{
    $svc = $null;   
    Write-Host "Connecting to CRM $CrmInstance";
    $svc = GetS2SService;
    return $svc;
}

#Main Method.
function Main (){
    $counter = 0;
Write-Host "Connecting to the CRM $CrmInstance ";
try{
    $svc = GetS2SServiceOrgWebProxy;
     
     #Fetch XML For Retrieving Event Process Records.
    $fetchAccountXML = @("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='accountnumber' />
<attribute name='accountname' />
<attribute name='accountid' />
<filter type='and'>
<condition attribute='accountnumber' operator='eq' value='1000' />
</filter>
</entity>
</fetch>"); $fetchAccount = [string]::Format($fetchAccountXML); #FetchExpression object $fetchExpression = New-Object Microsoft.Xrm.Sdk.Query.FetchExpression -ArgumentList ($fetchAccount); #get EntityCollection $objAccountData = $svc.RetrieveMultiple($fetchExpression); #Verifying Count Of Retrieved Records. if ($objAccountData.Entities.Count -gt 0) { $recordCount = $objAccountData.Entities.Count; Write-Host "Total Number Of Account Records : $recordCount"; foreach ($accountRecord in $objAccountData.Entities) { $accountId = $accountRecord.Id; #Declaring Entity. $eMail = New-Object Microsoft.Xrm.Sdk.Entity("email") $eFromActivityParty = New-Object Microsoft.Xrm.Sdk.Entity("activityparty") $eToActivityParty = New-Object Microsoft.Xrm.Sdk.Entity("activityparty") $guid = $accountRecord.Attributes["accountid"]; #Creating User Object (To Email). $lookupObjectA = New-Object -TypeName Microsoft.Xrm.Sdk.EntityReference; $lookupObjectA.LogicalName = "systemuser"; $lookupObjectA.Id = "1f6311ff-r218-f922-a9h6-111d3a454d54"; #Creating User Object (From Email). $lookupObjectB = New-Object -TypeName Microsoft.Xrm.Sdk.EntityReference; $lookupObjectB.LogicalName = "systemuser"; $lookupObjectB.Id = "zx461rff-f238-h922-a9h6-111d3a454d54"; $eFromActivityParty["partyid"] = [Microsoft.Xrm.Sdk.EntityReference] $lookupObjectA; $eToActivityParty["partyid"] = [Microsoft.Xrm.Sdk.EntityReference] $lookupObjectB; #Setting Up Attributes. $eMail["from"] = New-Object Microsoft.Xrm.Sdk.Entity $eFromActivityParty; $eMail["to"] = New-Object Microsoft.Xrm.Sdk.Entity $eToActivityParty ; $eMail["subject"] = "Testing Subject"; $eMail["description"] = "Testing Decription"; $eMail["regardingobjectid"] = New-Object Microsoft.Xrm.Sdk.EntityReference -ArgumentList ("account",$accountId); #Initiating Email. $emailId = $svc.Create($eMail); $sendEmailRequest = New-Object Microsoft.Xrm.Sdk.SendEmailRequest { EmailId = $emailId, TrackingToken = "", IssueSend = $true }; #Sending Final Email Activity Request. $sendEmailresp = Microsoft.Xrm.Sdk.SendEmailResponse $svc.Execute($sendEmailRequest); } } } catch { Write-Host "$_.Message"; } } Main;

 

CRM Crate

All In One Platform For Learning Microsoft CRM.

Facebook
Twitter
LinkedIn
5 1 vote
Article Rating
Subscribe
Notify of
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Registrarse
7 days ago

Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

error: CRM Crate Security Engine - Disabled Right Click & Selection!

Congratulations!

Well Done,
Welcome to CRM Crate

Stay tuned with us and get all latest updates and learning in Microsoft CRM and related techonologes.