oisinmc
oisinmc

Reputation: 31

Send-MailMessage: Cannot validate argument on parameter 'Subject'

This error appears when running the script below:

Send-MailMessage : Cannot validate argument on parameter 'Subject'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

The email still sends successfully and the subject appears correctly.

$dir = "C:\Users\user\Desktop\Lists\TodaysLists"
$SMTPServer = "192.168.1.111"
$Time = (Get-Date).ToString('MM/dd/yyyy hh:mm tt')

$japan = @{            
    Name = 'Japan'
    From = "[email protected]
    To   = "[email protected]"
    Cc   = "[email protected]"
}

$ireland = @{            
    Name = 'Ireland'
    From = "[email protected]
    To   = "[email protected]"
    Cc   = "[email protected]"
}

$Regions = @()
$Regions += New-Object PSObject -Property $japan
$Regions += New-Object PSObject -Property $ireland

foreach ($Region in $Regions) {
    $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse
    $AttachmentName = $Attachment.BaseName
    $Subject = "$AttachmentName"
    $Body = "Please find attached the Report for $($Region.Name).

Produced @ $Time 

Regards,
John Doe
"
    Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
    $Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
}

Upvotes: 1

Views: 5814

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23355

My guess would be that $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse is not returning any files for one or more of the regions, so $Subject ends up being $null.

You could either check for that state and perhaps throw a warning instead of attempting to send the mail, or another way to work around the error (and get an email sent but with a blank subject) would be to add some other (guaranteed) text to $subject. E.g:

$Subject = "$($Region.Name): $AttachmentName"

Although then I suspect it would complain about -Attachments being null.

To add a check/throw warning, you could do the following:

foreach ($Region in $Regions) {
    $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse

    If ($Attachment) {

        $AttachmentName = $Attachment.BaseName
        $Subject = "$AttachmentName"
        $Body = "Please find attached the Report for $($Region.Name).

    Produced @ $Time 

    Regards,
    John Doe
    "
        Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
        $Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
    } Else {
        Write-Warning "One or more files named $($Region.Name) were not found in $dir. Mail not sent."
    }
}

Upvotes: 2

Related Questions