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
[email protected],"[email protected],[email protected]",test.test
[email protected],"[email protected],[email protected]",new.test
[email protected],"[email protected],[email protected]",prod.test
[email protected],"[email protected],[email protected]",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: "[email protected],[email protected]" -- Will not work "[email protected]","[email protected]" -- 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
[email protected],"[email protected],[email protected]",test.test
'@ | Out-File $tempfile -Encoding utf8

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

    }
    Send-MailMessage @mailparams
}