0
votes

I have a *.csv file with a few columns and I want to use the UsersTo and UsersCc list of users to send messages. The problem is with $CcAddress as I have multiple email address once I format them I get the following : error: Send-MailMessage : An invalid character was found in the mail header: ','. At C:\Discovery Scan Process\RSU notifications\Notifications.ps1:43 char:2

  • Send-MailMessage -Encoding UTF32 -to $ToAddress -Cc $CcAddress -from $FromAddre ...
  •   + CategoryInfo          : InvalidType: (:) [Send-MailMessage], FormatException
      + FullyQualifiedErrorId : FormatException,Microsoft.PowerShell.Commands.SendMailMessage
    
    
    
    

CSV looks like this:

UsersTo,UsersCc,Domain
unknowTest.Test@test.com,"testOpen@new.com,Pvo.ovi@new.com",test.test
unknowNew.test@test.com,"testOpen@new.com,testOpen@new.com",new.test
unknowprod.mx@test.com,"testOpen@new.com,Evo.x@new.com",prod.test
unknowX.SS@test.com,"testOpen@new.com,Spekor1.@new.com",uat.test

Code:

$notificaitonList =  import-csv .\'listOfUsers - Copy.csv'
$domains = 'test.test','prod.test'

foreach ($domain in $domains){
 
$FromAddress = "some@address"
$ToAddress = ($notificaitonList | Where-Object {$_.domain -like $domain}).UsersTo | foreach {"`"$_`""}
$Ccstr = (($notificaitonList | Where-Object {$_.domain -like "$domain"}).UsersCc).split(",")
$Ccstr = $Ccstr  | foreach {"`"$_`""}
[string[]]$CcAddress= $Ccstr.Split(",") | foreach {"`"$_`""}


[string] $MessageSubject = "MessageSubject "
[string] $emailbody = "emailbody"
$SendingServer = "server"

Send-MailMessage -Encoding UTF32 -to $ToAddress -Cc $CcAddress -from $FromAddress -subject $MessageSubject -smtpServer $SendingServer -body $emailbody  

 }
1
If cc takes multiple values then just send it as is, don’t split it. - Doug Maurer
Thanks Doung, Unfortunately I doesn't it has to be a specific format for CC to accept multiple addresse. Example: "testOpen@new.com,Pvo.ovi@new.com" -- Will not work "testOpen@new.com","Pvo.ovi@new.com" -- Will work. The only way I could think of to make it look proper is by splitting it. - Evo
Oh I see, thanks for clarifying. - Doug Maurer

1 Answers

2
votes

You can simply split at the comma and let powershell handle the rest. Here is my test that confirmed this.

$tempfile = New-TemporaryFile

@'
UsersTo,UsersCc,Domain
some@email.com,"second@email.com,random@otherdomain.com",test.test
'@ | Out-File $tempfile -Encoding utf8

Import-CSV $tempfile | foreach {
    $mailparams = @{
        SMTPServer = 'myexchangeserver'
        From    = "noreply@email.com"
        To      = $_.usersto
        CC      = $_.userscc -split ','
        Subject = 'test email'
        Body    = 'test body'

    }
    Send-MailMessage @mailparams
}