#Sets attribute emailfrom as todays date. This will be added to the SMTP address so the mails cannot be marked as junk.
$emailfrom = Get-Date -Format ddMMMyy
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
#Set mail server and content details
$SmtpClient.Host = "ENTER YOUR BRIDGEHEAD OR SMTP RELAY SERVER HERE" # "somerelay@domain.com"
#I added the date field in the format DDMMMYY at the request of my manager as he wanted to make sure the sender address couldnt be blocked by the recipients
#If you want to be really mean you can also add this into the subject etc so the junk filters cant be used
$mailmessage.from = $emailfrom+"@ENTER YOUR EMAIL DOMAIN HERE" #$emailfrom+"@domain.com"
$mailmessage.To.add("firstemailaddress@domain.com,
secondemail@domain.com,
third@someotherdomain.com") #Enter the email addresses you want to recieve the mail seperated by a ,
$mailmessage.Subject = "Blackberry Server License Report"
#Static value of our current licences. I dont have a way to pull this from the BES as I have yet to find a table or item which holds this in the database so this needs to be manually updated if we purchase more.
#If anyone finds a way please let me know

$TotalLicense = "Total Licenses : 1480"
#Setup Database connection
$SQLSERVER="DBServer\DBServerInstance" #Enter your Server and instance details. BESDBServer\BESInstance
$Database="BlackberryDatabaseName" #Enter your BesMGMT Database name
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
#Run SQL Query to obtain all DeviceID's (PIN numbers) from the user tables
$SqlCmd.CommandText = "SELECT DeviceUserID FROM UserConfig"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$Listvalue=$DataSet.Tables[0]| format-list
#Takes a count of the number of records in the dataset to confirm current number of devices in use hence licences used by the server.
#Remove 4 from count to remove the added lines from the header that would throw off the count. This is static -4
$usedcount = $Listvalue.count
$usedcount = $usedcount-4
#Build a string to send out in the email to the recipients above. firstemailaddress, second, third.....
$LicenseUsed = "Total Licenses Used : " + $usedcount
$mailmessage.Body = $LicenseUsed + "`r`n" + $TotalLicense + "`r`n" + "Please be ready to buy new Licenses"
$smtpclient.Send($mailmessage)