Test email from SharePoint using PowerShell


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.

I hope you find this useful and thanks for reading!


Comments (4)

  1. Yogesh Sapre says:

    Excellent Script, Very Helpful!!

  2. Egil Hansen says:

    Hi Mike,

    Thanks for the script. A small note though. It looks like you are only disposing of $web if emailing goes well, and not if it fails. I think you need to move the last `$web.Dispose()` outside of the last `else` block, such that is independent of the result of the email test.

Skip to main content