Test email from SharePoint using PowerShell

This post has been republished via RSS; it originally appeared at: SharePoint Support Blog articles.



The following PowerShell script was written for my post on configuring TLS between SharePoint and Exchange. However, since it was buried in process, I wanted to create a separate post just sharing the script, because it will be easier to maintain and use separately when needed.


Why use a script anyway?


I find this script very useful when testing mail flow from Sharepoint since it uses the "SPUtility::SendEmail" API , sends mail, captures the correct logs and presents them by launching notepad, all from a single server.


The Script:


# check to ensure Microsoft.SharePoint.PowerShell is loaded 
 $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
 if ($snapin -eq $null) {
 Write-Host "Loading SharePoint Powershell Snapin"
 Add-PSSnapin Microsoft.SharePoint.Powershell

 While ($web -eq $null){
 $web = Get-SPWeb (Read-Host "Input SPWeb URL using http://")

$email = (Read-Host "Input E-mail recipient")
$subject = (Read-Host "Input E-mail Subject")
$body = (Read-Host "Input E-mail Body")

#specify start time of action
 $StartTime = (Get-Date).AddMinutes(-1).ToString()

# Try sending e-mail via SharePoint.
 $send = [Microsoft.SharePoint.Utilities.SPUtility]::SendEmail($web,0,0,$email,$subject,$body)

#what to do if it fails
 if ($send -eq $false -and $web -ne $null){
 write-host "It didn't work, checking ULS for errors. Please stand by..." -foregroundcolor Red -backgroundcolor Yellow

#specify end time of action
 $EndTime = (Get-Date).AddMinutes(+1).ToString()

#make dir if it does not exist
 $TARGETDIR = "c:\logs"
 if(!(Test-Path -Path c:\logs)){
 New-Item -ItemType directory -Path $TARGETDIR

#finding error and creating log
 start-sleep 5
 Get-SPLogEvent -StartTime $StartTime -EndTime $EndTime | Where-Object {$_.Category -eq "E-Mail"} | Export-Csv -LiteralPath "$TARGETDIR\log.csv"

#starting notepad to open log
 start notepad.exe "$TARGETDIR\log.csv"

#what to do if it works
 if ($send -eq $true -and $web -ne $null){
 write-host "It Worked..Congrats!" -foregroundcolor DarkGreen -backgroundcolor White





As you can see below the script will ask for input and you will specify the SPWeb url, E-Mail recipient, E-Mail Subject and E-Mail Body. If you enter the SP Web url incorrectly, it will keep asking. Also, if the e-mail is not sent, you will be notified on screen and NOTEPAD will pop-up with the associated ULS logs.



REMEMBER: these articles are REPUBLISHED. Your best bet to get a reply is to follow the link at the top of the post to the ORIGINAL post! BUT you're more than welcome to start discussions here:

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