PowerShell to send email from SharePoint online demo output

2 ways instantly PowerShell to send email from SharePoint Online

No comments

Loading

In this “send email from SharePoint Online” post, I will share how we can send emails from SharePoint Online using PowerShell script (CSOM) code programmatically and using the PnP PowerShell commands.

PowerShell to send email from SharePoint Online

Use the below PowerShell to send email from SharePoint Online:

CLS
#Load SharePoint CSOM Assemblies
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$fileName = "Email_Sending_Report"
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path 

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
            
        }   
        
$logPath = $directoryPathForLog + "\" + $logFileName  
$isLogFileCreated = $False 

#DLL location
$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL
               
        } 

#DLL location
$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime
  
function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
} 
#variables region.
$siteURL="https://globalsharepoint.sharepoint.com/sites/TestSite/"
$spUserName="yourSharePointonlineaccount@yourtenantdomain.com"
$BCCUserName = "Global-sharepoint@globalsharepoint.onmicrosoft.com"
$ccUserName = "Global-sharepoint@globalsharepoint.onmicrosoft.com"
$toUserName = "Global-sharepoint@globalsharepoint.onmicrosoft.com"
$emailBody = "Test email from SharePoint online CSOM PowerShell script." 
$password = "YourPassword"
#variables region end.
$securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
  
#Setup the Context
try
{
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($spUserName, $securePassword)  
$clientCSOMEMailProperties=New-Object Microsoft.SharePoint.Client.Utilities.EmailProperties        
$clientCSOMEMailProperties.BCC= [Collections.Generic.List[String]]@($BCCUserName) 
$clientCSOMEMailProperties.CC=[Collections.Generic.List[String]]@($CCUserName) 
$clientCSOMEMailProperties.To=[Collections.Generic.List[String]]@($ToUserName) 
$clientCSOMEMailProperties.From=$spUserName 
$clientCSOMEMailProperties.Body=$emailBody
$clientCSOMEMailProperties.Subject="Test email from SharePoint online CSOM PowerShell script." 
$csomUtility=[Microsoft.SharePoint.Client.Utilities.Utility]::SendEmail($ctx, $clientCSOMEMailProperties)        
$ctx.ExecuteQuery() 
$ctx.Dispose() 
}
catch 
{
  
    $errorMessage = $_.Exception.Message +"in sending email from CSOM SharePoint online";
    Write-Host $errorMessage -BackgroundColor Red
    Write-Log $errorMessage 
}         
Write-Host "##########################################################"
Write-Host "Test email from SharePoint online CSOM PowerShell script." -ForegroundColor Green 
Write-Host "##########################################################"

Test – Script execution: send email from SharePoint Online using PowerShell script

Below is the send email from SharePoint Online using PowerShell script execution status:

send email from SharePoint online using PowerShell script

Output: PowerShell to send email from SharePoint online

PowerShell to send email from SharePoint online demo

PnP command to send email from SharePoint online: Send email using the PnP command 

Send-PnPMail -To address@tenant.sharepointonline.com -Subject test -Body test

Sends an e-mail using the SharePoint SendEmail method using the current context. E-mail is sent from the system account and can only be sent to accounts in the same tenant.

Send-PnPMail -To address@contoso.com -Subject test -Body test -From me@tenant.onmicrosoft.com -Password xyz

Sends an e-mail via Office 365 SMTP and requires a from address and password. E-mail is sent from the “from” user and can be sent to both internal and external addresses.

Send-PnPMail -To address@contoso.com -Subject test -Body test -From me@server.net -Password xyz -Server yoursmtp.server.net

Sends an e-mail via a custom SMTP server and requires a from address and password. E-mail is sent from the “from” user.

Summary: PowerShell script to send email from SharePoint online

Thus, in this article, we have learned about how we can send emails from SharePoint Online using the PowerShell script and PnP PowerShell command.

See Also: SharePoint Online PowerShell

You may also like the below SharePoint Online PowerShell tutorials:

 

Download SharePoint Online PDF Book

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

About Post Author

Do you have a better solution or question on this topic? Please leave a comment