troubleshooting Question

Powershell - send to multiple recipients

Avatar of Kent Dyer
Kent DyerFlag for United States of America asked on
PowershellShell ScriptingScripting Languages
9 Comments1 Solution3763 ViewsLast Modified:
I have been playing with PowerShell's Send-MailMessage and seems to work fine with one person to send to..  I have previously used Blat.exe with VBScript and it works fine.  I even tried to convert the Blat Script over to PowerShell..

I have also seen this, but does not seem to work either..
http://powershell.com/cs/blogs/tips/archive/2012/04/23/sending-email-to-multiple-recipients.aspx

I have read that you need to setup multiple recipients in the following manner:
$To = ("recipient1@company.com","recipient2@company.com")

If I convert the blat Script..
function blat-Mail
{
	param(
		[Parameter(Mandatory = $true)]
		[String[]]
		$To,
		[Parameter(Mandatory = $true)]
		$Subject, 
		[Parameter(Mandatory = $true)]
		$Body, 
		[Parameter(Mandatory = $true)]
		$Attachment, 
		$From = "CustomerCare@somecompany.com",
		$SmtpServer="RELAY.COMPANY.COM"
		)
			
	try {
		$strCommand = """D:\WORK\Scripts\Blat.exe"
		$strCommand = $strCommand + " -log $MailResult"
		$strCommand = $strCommand + " -f ""$from"""
		$strCommand = $strCommand + " -to ""$To"""
		$strCommand = $strCommand + " -server ""$smtpserver"""
		$strCommand = $strCommand + " -subject ""$subject"""
		$strCommand = $strCommand + " -body ""$body"""
		$strCommand = $strCommand + " -attach ""$Attachment"""
		$strCommand = $strCommand + " -q"""

 & $strCommand
##write-host $strCommand
		Write-Host "Email successfully sent." -ForegroundColor Green
	}
	catch {
		Write-Host "Email did not go through: $_" -ForegroundColor Red
	}
	}

$FullDate = Get-Date -format "yyyyMMdd000000"
$applog = "D:\WORK\Scripts\p1\AppLog\"
$mailresult = "$applog"+$FullDate+"_MailResult.txt"

blat-Mail "recipient1@company.com" "Daily Reports" "Attached are reports.  If there are any issues or concerns please contact your Customer Service Representative immediately." "D:\WORK\Scripts\p1\ReportDownload\Temp\20130713_foo.zip"

Open in new window


Results are (have tried to pass individual parameters and the whole thing as one parameter):
D:\WORK\ps\Reports\kt.ps1
Email did not go through: The term '"D:\WORK\Scripts\Blat.exe -log D:\WORK\Scripts\p1\AppLog\20130715000000_MailResult.txt -f "Cust
omerCare@somecompany.com" -to "recipient@fcompany.com" -server "RELAY.company.COM" -subject "Daily Reports" -body "Attached are
 reports.  If there are any issues or concerns please contact your Customer Service Representative immediately." -attach "D:\W
ORK\Scripts\p1\ReportDownload\Temp\20130713_foo.zip" -q"' is not recognized as the name of a cmdlet, function, script fil
e, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Multiple recipients using Send-MailMessage:

I am reading in a "mapping" (settings) file as well.

Mapping Construct is:

COMPANY1,recipient1@somecompany.com;recipient2@somecompany.com
COMPANY2,recipient1@anothercompany.com;recipient2@anothercompany.com;recipient3@anothercompany.com;recipient4@anothercompany.com
COMPANY3,recipien1@yetanothercompany.com

And here is the code..
#7 Email the resulting Zip files to companies
## to do: work on event log
$ScriptDir = Split-Path $MyInvocation.MyCommand.Path
#$applog = "$ScriptDir\AppLog\"
$applog = "D:\WORK\Scripts\p1\AppLog\"
#$bkup = "$ScriptDir\ReportDownload\BkUp\"
$bkup = "D:\WORK\Scripts\p1\ReportDownload\BkUp\"
#$temp = "$ScriptDir\ReportDownload\Temp\"
$temp = "D:\WORK\Scripts\p1\ReportDownload\Temp\"
#$Settings = "$ScriptDir\Settings.Txt"
$Settings = "D:\WORK\Scripts\Settings.Txt"

#READ IN SETTINGS FROM TEXT FILE
$setting = Get-Content $Settings -encoding String
foreach ( $set in $setting )
{
If ($set.split("=")[0] -eq "AdminRecipient")
{
$AdminRecipient = $set.split("=")[1]
}
If ($set.split("=")[0] -eq "smtpserver")
{
$smtpserver = $set.split("=")[1]
}
}

$FullDate = Get-Date -format "yyyyMMdd000000"

$Mapping = "D:\WORK\Scripts\p1\Mapping.Txt"
##$Mapping = "D:\WORK\Scripts\p1\Testing.Txt"
$mailresult = "$applog"+$FullDate+"_MailResult.txt"

# $sw = [Diagnostics.Stopwatch]::StartNew()
% { $i = 1 }
$DateLogged = Get-Date -format u
"Run Start: $DateLogged" | Out-File -append -filepath $MailResult -encoding ASCII
#NEED TO CHECK FOR THE EXISTENCE OF THE Mapping file
If (Test-Path $Mapping) {
$results=''
$count = @(Get-Content $Mapping).Length
$lists = Get-Content $Mapping -encoding String
"Number of COMPANIES: " + $count | Out-File -append -filepath $MailResult -encoding ASCII
foreach ($list in $lists)
{
	$CompanyName = $list.split(",")[0]
	$Email = $list.split(",")[1]
    	#IF  THERE ARE MORE THAN ONE $EMAIL IN THE RECIPIENT LIST AND CONTAIS A ; IT NEEDS TO BE REPLACED
	$files = Get-ChildItem -Path $temp
	# verify if the list of source files is empty
	foreach ($file in $files)
	##if ($file -ne $null)
	{
	   $filename = $file.name
	   $fullname = $file.FullName
	   #Need to check to be sure that the file has not been previously sent
	   $ORGName = $filename.Substring(0, $filename.length-4)
	   $ORGName = $ORGName.Substring(9, $ORGName.length-9)
	   $result = Test-Path $BkUp$ORGName\$filename
	   if (!(Test-Path $BkUp$ORGName\$filename))
	   {
	   $count = $file.count
	   $e = $filename.contains($CompanyName)
	   if ($CompanyName -eq $ORGName)
	   ##if ($e -eq $true)
	   {
        If ($Email.contains(";"))
        {
            $Email=$Email -replace(';',""", """)
        }
        
        #ForEach ($y in $Email) {
	#if($results -ne '') { $results += "','" }
	#$tmpy = $y
	#$results += $tmpy
	#}
	$Email=$Email -replace '([^_]*).*','"$1'
	$Email=($Email)

	##$Email=$Email -replace (';',"','")

	Write-host ($Email)
	$DateLogged = Get-Date -format u
	Send-MailMessage -To ($Email) -From "CustomerCare@company.com" -subject "Daily Reports for $ORGName" -Body "Attached are Daily reports.  If there are any issues or concerns please contact your Customer Service Representative immediately." -Attachment $fullname -smtpServer "$smtpserver"
	#####"$i ,On: "+Get-Date+" ,e-mail was sent for: $ORGName ,To: $EMail ,Attachment: $fullname" | Out-File -append -filepath $MailResult -encoding ASCII
	"$i,On: $DateLogged,e-mail was sent for: $ORGName,To: $EMail,Attachment: $fullname" | Out-File -append -filepath $MailResult -encoding ASCII
	$i++
        }
	}
    }
	}
#$sw.Stop()
##$sw.Elapsed
"" | Out-File -append -filepath $MailResult -encoding ASCII
#"time taken: " + $sw.Elapsed | Out-File -append -filepath $MailResult -encoding ASCII
"Number of Companies: " + $count | Out-File -append -filepath $MailResult -encoding ASCII

#Measure-Command { Get-Process }
#$timetaken = Measure-Command { Get-Process }

#http://social.technet.microsoft.com/Forums/windowsserver/en-US/e172f039-ce88-4c9f-b19a-0dd6dc568fa0/writing-to-different-event-logs-and-sources-registered-to-a-single-event-log
$src = [System.Diagnostics.EventLog]::SourceExists("Daily_reports")
#IF THE EVENTLOG DOES NOT EXIST, WE NEED TO CREATE IT
	if (!$src)
	{
		New-EventLog -source "Daily_Reports" -logname "Application" > $null
	}
	write-eventlog -logname "Application" -source "Daily_Reports" -eventID 3001 -entrytype "Information" -message "Daily Reports have been sent and process is complete." -category 1 -rawdata 10,20
}

Open in new window


Here are the results..
PS C:\Documents and Settings\kent> D:\WORK\ps\Reports\7-b.ps1
"recipient1@anothercompany.com", "recipient2@anothercompany.com", "recipient3@anothercompany.com", "recipient4@anothercompany.com"
Send-MailMessage : The specified string is not in the form required for an e-mail address.
At D:\WORK\ps\Reports\7-b.ps1:160 char:25
+            Send-MailMessage <<<<  -To ($Email) -From "CustomerCare@company.com" -subject "Daily Reports for $ORGName" -Body
 "Attached are Daily reports.  If there are any issues or concerns please contact your Customer Service Representative immediately
." -Attachment $fullname -smtpServer "$smtpserver"
    + CategoryInfo          : InvalidType: (:) [Send-MailMessage], FormatException
    + FullyQualifiedErrorId : FormatException,Microsoft.PowerShell.Commands.SendMailMessage
 
Send-MailMessage : A recipient must be specified.
At D:\WORK\ps\Reports\7-b.ps1:160 char:25
+            Send-MailMessage <<<<  -To ($Email) -From "CustomerCare@company.com" -subject "Daily Reports for $ORGName" -Body
 "Attached are Daily reports.  If there are any issues or concerns please contact your Customer Service Representative immediately
." -Attachment $fullname -smtpServer "$smtpserver"
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], InvalidOperationExceptio
   n
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.SendMailMessage

Thanks,

Kent
ASKER CERTIFIED SOLUTION
David Carr
Messaging Administrator

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 9 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 9 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros