
Creating an automated email notification system for document approval in SAP Business One using PowerShell can streamline your business processes and ensure that documents are approved promptly. In this tutorial, I'll guide you through the complete process, including setting up the database, creating a PowerShell script, and running it as a service.
We'll accomplish the following:
To begin, you'll need to create a User Defined Table (UDT) in SAP Business One that will keep track of the emails sent. This will prevent duplicate notifications for the same document.
Log into SAP Business One.
Navigate to: Tools > Customization Tools > User-Defined Tables - Setup.
Create a New Table with the following details:
Add Fields to the Table:
We'll create a PowerShell script that connects to the SQL Server database, retrieves documents awaiting approval, and sends email notifications.
Here's the complete script:
# Main loop to run every 5 minutes
while ($true) {
# Define SQL Server connection parameters
$serverInstance = "<Database Server Name>"
$database = "<Database Name>"
$username = "<UserName>"
$password = "<Password>"
$query = @"
SELECT T0.[WddCode], T0.[DocEntry], T0.[ObjType], T0.[DocDate], T0.[CreateDate], T0.[CurrStep], T1.[UserID], T2.[U_NAME], T2.[E_Mail] as "Email"
FROM OWDD T0
INNER JOIN WDD1 T1 ON T0.[WddCode]= T1.[WddCode] AND T0.[CurrStep]=T1.[StepCode]
INNER JOIN OUSR T2 ON T1.[UserID] = T2.[USERID]
LEFT JOIN [dbo].[@Z_APPR_EMAILS] T3 ON T3.[U_userid]=T1.[UserID] AND T3.[U_internalNumber]=T0.[WddCode] AND T3.[U_ObjType]=T0.[ObjType]
WHERE T0.[Status] ='W' AND T0.[WddCode]=4 AND T3.[Code] IS NULL
"@
# Create SQL connection string
$connectionString = "Server=$serverInstance;Database=$database;User ID=$username;Password=$password;"
# Create SQL connection
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
# Create SQL command
$command = $connection.CreateCommand()
$command.CommandText = $query
# Open SQL connection
$connection.Open()
# Execute SQL query
$reader = $command.ExecuteReader()
# Process query results and send email notifications
if ($reader.HasRows) {
Write-Host "Query Results:"
while ($reader.Read()) {
$row = @{
WddCode = $reader["WddCode"]
DocEntry = $reader["DocEntry"]
ObjType = $reader["ObjType"]
DocDate = $reader["DocDate"]
CreateDate = $reader["CreateDate"]
CurrStep = $reader["CurrStep"]
UserID = $reader["UserID"]
U_NAME = $reader["U_NAME"]
Email = $reader["Email"]
}
Write-Output $row
# Send email notification
$to = $row.Email
$subject = "Document Approval Notification"
$body = "Hello $($row.U_NAME),<br><br>A document is waiting for your approval, "
$body += "please log in to the system to review and approve this document.<br><br>Regards,<br>SAP automatic notification"
Send-MailMessage -To $to -From "sap.notification@yourcompany.com" -Subject $subject -Body $body -BodyAsHtml -SmtpServer "smtp.yourcompany.com"
# Calculate the current time in hours and minutes combined into a single integer
$currentDateTime = Get-Date
$currentTime = $currentDateTime.ToString("HHmm")
# Calculate the current date in YYYYMMDD format
$currentDate = $currentDateTime.ToString("yyyyMMdd", [System.Globalization.CultureInfo]::InvariantCulture)
# Close the DataReader before executing the insert command
$reader.Close()
# Get the latest Code number
$maxCodeQuery = "SELECT MAX(CAST(Code AS INT)) FROM [dbo].[@Z_APPR_EMAILS]"
$maxCodeCommand = $connection.CreateCommand()
$maxCodeCommand.CommandText = $maxCodeQuery
$latestCode = $maxCodeCommand.ExecuteScalar()
$newCode = $latestCode + 1
# Insert line into the database
$insertQuery = "INSERT INTO [dbo].[@Z_APPR_EMAILS] (Code, Name, U_email, U_userid, U_internalNumber, U_ObjType, U_status, U_sentDate, U_sentTime) VALUES ('$newCode', '$newCode', '$to', '$($row.UserID)', '$($row.WddCode)', '$($row.ObjType)', 'Sent', $currentDate, $currentTime)"
$insertCommand = $connection.CreateCommand()
$insertCommand.CommandText = $insertQuery
$insertCommand.ExecuteNonQuery() | Out-Null
Write-Host "Line inserted into database for document $($row.DocEntry)." -ForegroundColor Cyan
# Reopen the DataReader after executing the insert command
$reader = $command.ExecuteReader()
}
} else {
Write-Host "No documents awaiting approval found." -ForegroundColor Yellow
}
# Close SQL reader and connection
$reader.Close()
$connection.Close()
# Sleep for 5 minutes before next iteration
Start-Sleep -Seconds 300
}
Connection Parameters: Establish a connection with your SQL Server database by providing server instance, database name, username, and password.
SQL Query: Retrieve documents awaiting approval. This query checks if the document's status is 'W' and if no entry exists in the @Z_APPR_EMAILS table.
Sending Emails: For each document found, the script sends an email using Send-MailMessage.
Logging: After sending the email, the script logs the sent email details in the @Z_APPR_EMAILS table.
Continuous Execution: The script runs continuously in a loop with a 5-minute pause between iterations.
Creating a Windows service allows your script to run automatically without manual intervention. Follow these steps to create and manage the service.
Here's the script to set up your PowerShell script as a Windows service:
# Define service name and description
$serviceName = "EmailNotificationService"
$serviceDisplayName = "Email Notification Service"
$serviceDescription = "Service to send email notifications for document approval"
# Define script path
$scriptPath = "C:\scripts\SendEmailNotifications.ps1"
# Create service
New-Service -Name $serviceName -DisplayName $serviceDisplayName -Description $serviceDescription -BinaryPathName "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File $scriptPath" -StartupType
Create a Test Document for Approval:
Check for Email Notification:
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
10 | |
9 | |
7 | |
5 | |
4 | |
4 | |
3 | |
3 | |
3 | |
3 |