1

I try to write powershell code to send email from sharepoint online using CSOM.I get no error but doesn't work either. The logon works but not sending the email.

Add-Type -Path "$([Environment]::GetFolderPath('MyDocuments'))\WindowsPowerShell\Modules\SharePointOnline.CSOM\0.1.0\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$([Environment]::GetFolderPath('MyDocuments'))\WindowsPowerShell\Modules\SharePointOnline.CSOM\0.1.0\Microsoft.SharePoint.Client.Runtime.dll"

#Config Parameters                                                                 
$EmailFrom ="emailfrom"
$EmailTo = "emailto"
$Subject ="Subject"

Try 
{
$SiteUrl = "sharepoint teamsite"
$UserName="username"
$Password ="password"
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials


#Setup Email
$EmailProperties = New-Object Microsoft.SharePoint.Client.Utilities.EmailProperties
$EmailProperties.From = $EmailTo
$EmailProperties.To = [String[]] $EmailTo
$EmailProperties.Subject = $Subject
[Microsoft.SharePoint.Client.Utilities.Utility]::SendEmail($Context,$EmailProperties)
$Context.ExecuteQuery()

}
Catch
{
Exit
}

2 Answers 2

0

you have a few problems

  1. do not use try catch. you are effectively hiding the exception
  2. make sure the username is in the correct form (e.g. [email protected]) or you'll get

New-Object : Exception calling ".ctor" with "2" argument(s): "The 'username' argument is invalid."

  1. your "from" and "to" are both using the "to" variable. maybe fix that as well
2
  • Strange. Still doesn't work
    – user78519
    Oct 31, 2019 at 18:46
  • Strange. Now it does haha. Thanks for the help. Gr. Peter
    – user78519
    Oct 31, 2019 at 18:51
0

Please find the below code to send the email from SharePoint online using PowerShell CSOM.

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="[email protected]"
 $BCCUserName = "[email protected]"
 $ccUserName = "[email protected]"
 $toUserName = "[email protected]"
 $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="Test email from SharePoint online CSOM PowerShell script." 
 $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 "##########################################################"

Output:

Email sent from SharePoint online output

Reference URL:

https://global-sharepoint.com/2019/11/02/send-email-from-sharepoint-online-using-csom-powershell-script/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.