Automate Sitecore Workflow Approval Process and Email Report

Automation is the key to tech. It is the process by which tasks which were previously done by humans, are performed entirely by machines. In this post, I shall take you through how to automate Sitecore Workflow Approval for a more efficient way of working.

Why do you need Auto Approve?

Every project has a different set of requirements, and one of the requirements I was tasked to do was to automate the Workflow approval process. You may think, what is the purpose of having a workflow if you want things to be approved automatically. Well, as mentioned earlier, there are different scenarios that may deem such a requirement necessary.

It is not because of the risk in approving content that may be incorrect. It is due to that fact that there are a lot of items in the workflow coming in from the translation agency and in order to verify the content, it requires physical approval to push on to Stage. The automation to be implemented here will help us to know that translations are coming in and send it to the respective content team member to verify. Once verification is done, then in one simple, a user can push it Live.

I’m sure most of you have worked with the automation, but you’ll find something useful in this post. I wrote about Getting Sitecore Workflow Items in an earlier post,and now, you’ll see how you can automate the Sitecore Workflow Approval Process and send a report via email. As we have already established how to get the items, the next step is to approve the item state and it should happen automatically.

Automate

Automate:

Sitecore scheduler plays a big role in automating business processes such as creating reports daily or uploading feeds regularly on a timely basis, etc.

In order to automate the process, we have to:

  • Get Sitecore WorkFlow Items
  • Approve Workflow Items and add in the new list
  • Create Email Attachment-based on the list
  • Send Email
  • Create Scheduling Task

In the below script, you’ll have to modify the Workflow State ID with the one you want to change and also provide the proper command name at line 30.

In the script, I’m creating a list with three columns – Sitecore Item ID, Sitecore Item Path and URL. If the item has any rendering then add the URL in the report.
Note, that in the production script, I’ve written a custom logic for the URL. You might also have to add as per your need.
Furthermore, I’ll create an attachment, fetch the MailServer, Username, Password, and Port from the config file and send an email. You can also pass the values in the Script.

Modify the body message if there is no item for publishing. You should create the body message with a user interface designed in line with the company’s branded emailer.
“Good design is a lot like clear thinking made visual.” – Edward Tufte

Sitecore PowerShell Script:

$workflowStateID = Get-Item -Path master: -ID "{46DA5376-10DC-4B66-B464-AFDAA29DE84F}"
$referringItems = Get-ItemReferrer -Item $workflowStateID

$hasAnyItemInWorkflow = $false

#EmptyArray
$listofWorkflowItems = @()

#Skip System Items
Foreach($item in $referringItems) { 

    $itemPaths = $item.Paths.FullPath
    if($item.Paths.FullPath.contains('/sitecore/content/'))
    {
        if($hasAnyItemInWorkflow -ne $true)
        {
            $hasAnyItemInWorkflow = $true
        }

        $rendering = $item | Get-Rendering
        
        $addInList = New-Object System.Object
        $addInList | Add-Member -type NoteProperty -name ID -Value $item.ID
        $addInList | Add-Member -type NoteProperty -name Path -Value $item.FullPath
        
        if($rendering){
            $addInList | Add-Member -type NoteProperty -name URL -Value $item.FullPath.Replace("/sitecore/content/Home","https://www.nikkipunjabi.com")
        }
        
        #Provide Workflow State Command Name to Invoke
        Invoke-Workflow $item -CommandName "Approve" -Comments "Automated"
        
        $listofWorkflowItems += $addInList
    }
}
    $msg = new-object Net.Mail.MailMessage
    $msg.From = "sitecorebro@gmail.com"
    $msg.To.Add("nikki.punjabi+sitecorebro@gmail.com")
    $msg.Subject = "Sitecore Sample Workflow Automated Execution Report"
    
    if($hasAnyItemInWorkflow -eq $true){
        
        $msg.Body = "Please find the attachment for the Workflow Report."
        
        $title = "Workflow-Report"
        $datetime = Get-Date -format "yyyy-MM-d_hhmmss"
        
        $format = & ([scriptblock]::Create($exportProperty))
        $reportResult = [PSCustomObject]$listofWorkflowItems | 
            Select-Object -Property $format | 
            ConvertTo-Html -Head $head -Body $formattedBody -Title $title | 
            ForEach-Object { [System.Web.HttpUtility]::HtmlDecode($_) } | 
            Out-String
            
            $attachmentBytes = [System.Text.Encoding]::UTF8.GetBytes($reportResult)
            $memoryStream = New-Object System.IO.MemoryStream
            $memoryStream.Write($attachmentBytes, 0, $attachmentBytes.Length)
            $memoryStream.Seek(0, [System.IO.SeekOrigin]::Begin) > $null
            
            $contentType = New-Object "System.Net.Mime.ContentType"
            $contentType.MediaType = [System.Net.Mime.MediaTypeNames+Text]::Html
            $contentType.Name = "$title-$datetime.html"
            $attachment = New-Object System.Net.Mail.Attachment($memoryStream, $contentType)
            
            $msg.Attachments.Add($attachment)
    }
    else{
        $msg.Body = "No item found in the Sample Workflow."
    }

    #$SMTPServer = "smtp.gmail.com"
    
    $smtpServer = [Sitecore.Configuration.Settings]::GetSetting("MailServer")
    $smtpUsername = [Sitecore.Configuration.Settings]::GetSetting("MailServerUserName")
    $smtpPassword = [Sitecore.Configuration.Settings]::GetSetting("MailServerPassword")
    $smtpPort = [Sitecore.Configuration.Settings]::GetSetting("MailServerPort")
    $SMTPClient = New-Object Net.Mail.SmtpClient($smtpServer, $smtpPort)
    $SMTPClient.EnableSsl = $true
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword);

    $SMTPClient.Send($msg)

Once your script is ready, save it in Sitecore and create a scheduling task to automate the approval process.

Automated Sitecore Workflow ApprovalScheduler

I’m running the script every mid-night from Monday-Friday. You should define the time as per your need. Refer to Sitecore Scheduled Task – Schedule time format and other quirks for more details about Sitecore scheduled task time format and other quirks.

Output:
Automated Sitecore Workflow Email

In my actual script, I created a settings item from where I fetch all the required information, including the email body, workflow IDs and to: email, which is easier to maintain.
Also, I have written a .Net code for the system where there is no support of Sitecore PowerShell Extensions Module. Do shout in the comments if you need it.

Many thanks to Michael West for full support on Sitecore Powershell Extensions.

Good Reads:
https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/repost-all-about-sitecore-scheduling-agents-and-tasks
https://briancaos.wordpress.com/2017/08/18/sitecore-scheduled-task-schedule-time-format-and-other-quirks/
http://blog.nikkipunjabi.com/2017/07/schedule-publishing-items-in-sitecore.html

Happy Sitecoring!

One thought to “Automate Sitecore Workflow Approval Process and Email Report”

  1. Hi, I would like to share some of my thoughts concerning some of the best benefits for using automation. I belive that productivity and availability will definitely benefit from automation. Reliability is also an important factor and it can depend on other variables, but if a balance between it and performance is reached, you can definitely say that the recipe of success has been found.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.