I have a requirement to send email to thousands of different recipients with a different attachment to each of them.
I have the list of recipients in a text file and the list of attachment paths in another text file.
For the first recipient in the text file, first attachment path should be used.
For the second recipient in the text file, second attachment path should be used.
The code below sends all attachments to all recipients separately.
But I would like this to work as I described above. Only one email should be sent to each recipient with the corresponding attachment.
Please let me know if this is achievable. I can also copy the recipients and paths to attachments in two different columns of an Excel spreadsheet if it is possible with Excel.
I can achieve this by constructing thousand different send-mailmessage lines with Excel but that looks like an ugly way of doing. That's why I would like to know if there is a better way of doing this.
$attachments = get-content C:\attach.txt
$recipients = get-content C:\recip.txt
foreach ($attachment in $attachments)
{
foreach ($recipient in $recipients)
{
Send-MailMessage -From "recipient#target.com" -To $recipient -subject "Test" -smtpServer smtp.server.com -attachments $attachment
}
}
One possibility:
$MailParams =
#{
From = "recipient#target.com"
Subject = "Test"
SmtpServer = 'smtp.server.com'
}
$recipients = get-content C:\recip.txt
get-content C:\attach.txt |
foreach { $i=0 } { $_ | Send-MailMessage #MailParams -To $recipients[$i++] }
Use a for loop to iterate through both files in tandem:
for ($i = 0; $i -lt $recipients.Count; $i++) {
Send-MailMessage -From "recipient#target.com" -To $recipients[$i] -Subject "Test" -SmtpServer smtp.server.com -Attachments $attachments[$i]
}
Presumably the number of lines in both files should be the same, so $recipients.Count is the number of lines in both recip.txt and attach.txt; you could use $attach.Count in the for loop just as well.
You could also go the Excel route, but then save the file as a CSV to make things simpler. With a CSV file, you could use this code, where Recipient and Attachment are the column names:
Import-Csv <path_to_csvfile> | %{Send-MailMessage -From "recipient#target.com" -To $_.Recipient -Subject "Test" -SmtpServer smtp.server.com -Attachments $_.Attachment}
That's probably a better idea, because you're less likely to have mistakes matching the attachments to the right recipients if they're in the same file. With separate lists, one error could result in all recipients after that point receiving the wrong attachments.
Related
I have the following variable stored
PS C:>$PathArray
jagbir.singh1990#gmail.com
mr.singh#gmail.com
PS C:>$PathArray2
805775-1.zip
805775-2.zip
$Arrayresult = for ( $i = 0; $i -lt $max; $i++)
{
Write-Verbose "$($PathArray[$i]),$($PathArray2[$i])"
[PSCustomObject]#{
PathArray = $PathArray
PathArray2 = $PathArray2
}
PS C:>$Arrayresult
PathArray PathArray2
--------- ----------
{jagbir.singh1990#gmail.com, mr.singh#gmail.com...} {805775-1.zip, 805775-2.zip...}
{jagbir.singh1990#gmail.com, mr.singh#gmail.com...} {805775-1.zip, 805775-2.zip...}
I want to send email1 with body text containing zip file1 name and email2 with body text containing zip file2 name
Ex:
From : jagbir.singh1990#gmail.com
Body : 805775-1.zip file transfer successful.
No Attachments required
code:
foreach($X in $Arrayresult){
Send-MailMessage -From $X.Patharray -To 'jagbir.singh1990#gmail.com' -Subject 'File Transfer completed successfully' -body 'File $X.PathArray2 transfer success' -smtpServer 'smtp.gmail.com' -Port 465
}
Write-Host "Email sent.."
How can I seperate each email for each zip file
email1 --> file1
email2 --> file2
I'm not sure why you would want to keep the email addresses and filenames in separate arrays and then combine them in an array of PSObjects for this.
Anyway, the first mistake is that you did not specify a value for variable $max, which should be the count for the smallest of the two arrays (I'm using more descriptive variable names for these arrays):
$max = [math]::Min($email.Count, $files.Count)
The second one is that you are adding the complete arrays in the properties of each PSCustomObject you create instead of one element of the input arrays.
Finally, I would suggest using a simpler loop (not creating a new PSObject array), use Splatting for the parameters of Send-MailMessage and add some error checking while sending:
Something like:
# array of email addresses to send TO
$email = 'jagbir.singh1990#gmail.com', 'mr.singh#gmail.com'
# array of filenames to use in the mail body
$files = '805775-1.zip', '805775-2.zip'
# determine the max number of iterations
$max = [math]::Min($email.Count, $files.Count)
# set up a hashtable for splatting the parameters to the Send-MailMessage cmdlet
$mailParams = #{
From = 'me#gmail.com'
Subject = 'File Transfer completed successfully'
SmtpServer = 'smtp.gmail.com'
Port = 465
# other parameters go here
}
for ($i = 0; $i -lt $max; $i++) {
# inside the loop we add/update the parameters 'To' and 'Body'
$mailParams['To'] = $email[$i]
$mailParams['Body'] = "File $($files[$i]) transfer success"
try {
Send-MailMessage #mailParams -ErrorAction Stop
Write-Host "Email sent.."
}
catch {
Write-Error "Email NOT sent.`r`n$($_.Exception.Message)"
}
}
I'm attempting to create a Send-Email function in a script which can change the email address each time the script is used. However, I'm currently suck being forced to use a static email:
function Send-Email (
$recipientEmail = "EMAIL",
$subject = "Ticket" + $type,
$body
) {
$outlook = New-Object -ComObject Outlook.Application
$mail = $outlook.CreateItem(0)
$mail.Recipients.Add("EMAIL")
$mail.Subject = ("Ticket - " + $type)
$mail.Body = $body # For HTML encoded emails
$mail.Send()
Write-Host "Email sent!"
}
I'd like to set it up so that I can define $recipientEmail and then later use this input with $mail.Recipients.Add("EMAIL") - I've beend doing $mail.Recipients.Add("$receipientemail") and the like without any luck and wondering if I'm approaching this completely wrong?
I'd like it to be set up in a way that it could use
[void] $listBox.Items.Add("Email1")
[void] $listBox.Items.Add("Email2")
[void] $listBox.Items.Add("Email3")
And accept that as the email to send to instead of only working with one email.
This whole thing rang a bell with me, and I went "code dumpster diving". I wrote this same function (more or less) a year ago. I'm not using $mail.recipients.add(); I'm using $Mail.To = $RecipientEmail; if I want multiple recipients, I simply -join ";" them and assign to $mail.To. The members $mail.CC and $mail.BCC work the same way:
Function Send-Email {
<#
.Synopsis
Sends Email using Microsoft Outlook
.DESCRIPTION
This cmdlet sends Email using the Outlook component of a locally-installed
Microsoft Office. It is not expected to work with the "Click-to-run" versions.
This version requires that Outlook be running before using the cmdlet.
.PARAMETER To
Must be a quoted string or string array, may not be omitted.
Specifies the address to send the message to. If an array, it will
be converted to a semicolon-delimited string. May contain contact
groups.
.PARAMETER Subject
Must be a quoted string, may not be omitted.
Specifies the subject of the message to be sent.
.PARAMETER Body
Must be a string or a string array, may not be omitted.
Contains the text of the message to be sent. If supplied as a string in double
quotes, any PowerShell variables will be expanded unless the leading $ is
escaped. If supplied in a script via a variable containing a here-doc, will
reproduce the here-doc. If supplied as an array, either by variable or by the
Get-Content cmdlet, the array elements will be joined with `r`n as "separators".
A body supplied via Get-Content will not have expanded variables; arrays created
in scripts using double quotes or via here-docs willl have expanded variables.
.PARAMETER CC
Must be a quoted string or string array, may be omitted.
Specifies an address to send a copy of the message to. If an array, it will be
converted to a semicolon-delimited string. All recipients can see that a copy
of the message was sent to the addresses here.
.PARAMETER BCC
Must be a quoted string or string array, may be omitted.
Specifies an address to send a copy of the message to. If an array, it will be
converted to a semicolon-delimited string. The recipients named here are not
displayed as a recipient of the message, even though they do receive the message.
.PARAMETER Attachments
Must be a quoted string or string array, may be omitted.
Specifies one or more files to be included with the message as attachments.
.INPUTS
This version of the cmdlet does not accept input from the pipeline
.OUTPUTS
No output to the pipeline is generated. The cmdlet does return an error code.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body "I need a raise."
Sends an email with the indicated subject and body to the stated address.
.EXAMPLE
$messagebody = #"
Roses are red
Violets are blue
I need a raise
And so do you
"#
$others = "boss-of-boss#example.com","hr#example.com"
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -cc $others -Body $messagebody
Sends an email with the indicated subject to the stated address. The body
will be composed of the lines in the variable $messagebody as shown; the
line breaks are preserved. A copy of the message is sent to the two addresses
listed in $others.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body (Get-Content -Path "C:\Request-for-raise.txt")
Sends an email with the indicated subject and body to the stated address.
The body is drawn from the indicated file, and line breaks are preserved.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body "Please see attached for rationale for raise" -Attachments (Get-Content -Path "C:\Request-for-raise.txt")
Sends an email with the indicated subject and body to the stated address.
The indicated file is included as an attachment.
.NOTES
Planned Future Enhancements:
1. Allow the cmdlet to accept input (message body text) from the pipe.
2. Allow the cmdlet to accept the body from a file (parameter -BodyFromFile)
3. Allow the cmdlet to start up Outlook if it is not already running.
This includes shutting it down afterward.
4. Allow the body to be formatted as HTML or RTF, and properly handle this.
Initially, switches (e.g., -BodyAsHTML or -BodyAsRTF); better would be to
use file name (e.g., -BodyFromFile "C:\Test.html" would still set the message
format to HTML even in the absence of -BodyAsHTML); best would be to inspect
content of file.
Based on a script from http://www.computerperformance.co.uk/powershell/powershell_function_send_email.htm
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True)]
[String[]]$To,
[String[]]$CC,
[String[]]$BCC,
[Parameter(Mandatory=$True)]
[String]$Subject,
[Parameter(Mandatory=$True)]
[String[]]$Body,
[String[]]$Attachments
)
Begin {
# Future Enhancement: Start Outlook if it's not already running
} # End of initialization
Process {
# Create an instance Microsoft Outlook
$Outlook = New-Object -ComObject Outlook.Application
# Create a new mail message
$Mail = $Outlook.CreateItem(0)
# Set up the email
$Mail.To = $To -join ";"
if ($CC -ne $null) {
$Mail.CC = $CC -join ";"
}
if ($bcc -ne $null) {
$Mail.BCC = $BCC -join ";"
}
$Mail.Subject = "$Subject"
$Mail.Body = $Body -join "`r`n"
if ($attachments -ne $null) {
foreach ($Attachment in $Attachments) {
$silencer = $Mail.Attachments.Add($Attachment)
}
}
# I need to investigate scripting Outlook more.
# The next three comments may be all that's needed
# to handle HTML and/or attachments.
# $Mail.HTMLBody = "When is swimming?"
# $File = "D:\CP\timetable.pdf"
# $Mail.Attachments.Add($File)
# Place message in outbox.
$Mail.Send()
} # End of Process section
End {
# Clean up after ourselves. This prevents Outlook from reporting
# an error on exit.
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook)
$Outlook = $null
# If Outlook settings are to Send/Receive only on command rather
# than as-needed, force the send at this time.
# NOTE TO SELF: CHECK THIS!
# $Outlook.GetNameSpace("MAPI").SendAndReceive(1)
# If we launched Outlook at the beginning, close it here.
# $Outlook.Quit()
} # End of End section!
} # End of function
<#
Note 2: Look in Outlook's outbox for a newly-created message.
Note 3: If you really want to send the email then append this command:
$Outlook.GetNameSpace("MAPI").SendAndReceive(1)
#>
Im sending a testemail via powershell like
$messageParameters = #{
Subject = "Email Tool"
Body = Get-Content "C:\body.txt" | out-string
From = "Info <info#xy.de>"
To = "Me <me#xy.de>"
SmtpServer = "mail.xy.de"
Encoding = New-Object System.Text.UTF8Encoding
}
send-mailmessage #messageParameters -BodyAsHtml
everything is working find except the encoding.
if i don't use encoding some characters are send as ??
and if i use it, what i actually want to do, than i get this Ä Ö Ü
but it should be ä ö ü and not this above.
If i don't send the mail as HTML it works.
How can i send the mail with the right encoding AND as html ?
I believe the problem is that your text-file is getting jumbled when you are reading it into a variable as non-utf8.
I would try getting the text file as UTF-8 and keeping the Encoding line.
Body = Get-Content "C:\body.txt" -Encoding UTF8 | Out-String
EDIT: Added Out-String per Dwza.
i have a text file that is automatically downloaded and updated with Task Scheduler.
It looks like this:
C:\PrintLog\GetUsageReportFromPrinterWebService\10.22.17.102:58:<input type="hidden" name="AVAILABELBLACKTONER" value="60">
C:\PrintLog\GetUsageReportFromPrinterWebService\192.167.10.140:58:<input type="hidden" name="AVAILABELBLACKTONER" value="80">
C:\PrintLog\GetUsageReportFromPrinterWebService\192.167.14.128:58:<input type="hidden" name="AVAILABELBLACKTONER" value="80">
I would like to:
delete "C:\PrintLog\GetUsageReportFromPrinterWebService\" and "input type="hidden" name="AVAILIBLETONER""
replace that IP adress with printer name (example 10.51.17.122:58 equals HP-01, 192.168.10.150:58 equals HP-02 etc)
check if "value=" is smaller than 20 and if so than send an email with function sendMail
It doesn't matter what is in that email (after that I will check it manually with webservice anyway).
I just need this as an remainder/alerter that some printer is getting low on toner, so I am not forced to manually check that txt file everyday(I most certainly would forget that :) ). These printers are offsite so I need to know in advance that the printer is low.
Note1: There are empty lines and spaces at the beginning of that txt
Note2: And no, there is no send report via email when low on toner to be configured on those printers (I double checked).
Note3: using C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
I guess point one and two are optional. The third one is important for me, I googled for something similar but just got lost as everyone wanted something little bit different.
Thanks
Here's another possibility (I think it requires Powershell 4 because of Send-Mailmessage, but I could be wrong):
#requires -version 4.0
$logs = Get-Content "F:\scripts\ParseLog\file.log"
$warning = $false
$lowPrinters = ""
# Mail Settings
$Subject = "Low Toner Warning"
$To = "printeradmin#contoso.com"
$From = "admin#contoso.com"
$SMTPServer = "smtp.contoso.com"
$Priority = "High"
$printerList = #{
"10.51.17.122:58" = "HP-01";
"192.168.10.150:58" = "HP-02";
"10.22.17.102:58" = "HP-03";
"192.167.10.140:58" = "HP-04";
}
foreach ( $log in $logs ) {
if ( $log -match '^C:\\PrintLog\\GetUsageReportFromPrinterWebService\\([^:]+:[^:]+):.*value="(.*)">$' ) {
$printer = $Matches[1]
$toner = [int]$Matches[2]
}
if( $toner -lt 20 ) {
$warning = $true
if( $printerList.ContainsKey( $printer ) ) {
$printerName = $printerList[ $printer ]
} else {
$printerName = $printer
}
$lowPrinters += "Printer {0} has a low toner level of {1}.`n" -f $printerName, $toner
}
}
if( $warning ) {
Send-MailMessage -From $From -To $To -Subject $Subject -body $lowPrinters -SmtpServer $SMTPServer
}
Along about line 8 we setup some stuff for sending email. Starting at line 15, we build a hash table mapping printer IPs/Ports with Printer Names (since printer queues aren't always listed in DNS, I decided to use a hash table instead). On line 23, we use a regular expression to grab the ip and port, and the toner value by using the -match operator. Stuff grabbed by the regex is stored in an array called $Matches.
As an example, you could do something like this:
$filePath = "C:\updatedFile.txt"
$prefix = "C:\PrintLog\GetUsageReportFromPrinterWebService\"
$lines = Get-Content $filePath |Where-Object {$_.Trim() -like "$($prefix)*"}
foreach($line in $lines)
{
$content = $line.Trim().Substring($prefix.Length)
$parts = $content -split ":"
$inputML = [xml]"$($parts[2])</input>"
$inputValue = [int]$inputML.input.value
if($inputValue -lt 20)
{
$printer = [System.Net.DNS]::GetHostByAddress($parts[0]).HostName
<#
Your sendMail call in here
#>
}
}
You remove the "C:\PrintLog\GetUsageReportFromPrinterWebService\" part with Substring(), split it into 3 pieces, and then parse to last part as an xml element, giving much easier access to the value attribute
The IP to Printer name part will only work if you have reverse DNS in place already
I have the following code snippet from my PowerShell script that...
Loops through a list of servers
Does a Select-String -notmatch on the error log at each server
Flags the server if the error log is bad, and gives the OK if the error log if fine
What I'd like to also do is send an email report that enumerates each of the discovered bad error logs in a list, and also list all the servers whose error logs are OK. Something like this in the email body:
The following servers have bad error logs:
Server3
Server6
Server14
The following servers are OK:
Server1
Server2
Server5
Here is my code snippet:
$Servers = Get-Content $ServerLst
ForEach ($Server in $Servers)
{
$ErrorLog = Get-ChildItem -Path \\$Server\$LOG_PATH -Include Error.log -Recurse | Select-String -notmatch $SEARCH_STR
If ($ErrorLog)
{
Write-Host "Bad Error Log found at $Server!"
}
Else
{
Write-Host "Error log is OK."
}
}
I'm guessing I would need a Send-Mail function where I would pass in the server names with bad error logs, etc. However, I'm not quite sure how to approach this.
Any great ideas will be greatly appreciated. Thanks!
If you are using Powershell V1 use this function from the Powershell Cookbook to send mail. In Powershell V2 you can send mail using Send-MailMessage.
$Servers = Get-Content $ServerLst
$Bad = "The following servers have bad error logs:`n`n"
$OK = "`nThe following servers are OK:`n`n"
ForEach ($Server in $Servers)
{
$ErrorLog = Get-ChildItem -Path \\$Server\$LOG_PATH -Include Error.log -Recurse | Select-String -notmatch $SEARCH_STR
If ($ErrorLog)
{
$Bad += "`t - $Server`n"
}
Else
{
$OK += "`t - $Server`n"
}
}
Send-MailMessage -Body "$Bad $OK" -Subject "Bad Logs" -SmtpServer $servername -To $to -From $from
Remark: The smtpserver parameter is called smtphost in the Powershell cookbook function.
You will need to make the function on your own, but here is some pseudo code:
Function SendMail
{
Param(...your params here)
...send the mail...
}
<...
Your code to check all your servers
You need to save your errors or issues to an array or hashtable.
I'll assume you use a 2-field array called $ErrArray
...>
# Now at the end you build a string for the body of the email to incorporate your errors
$StrBody = "Bad Error Log Report`n`n"
$ErrArray | ForEach-Object {$StrBody = $Strbody + "`n$($_[0]) server had an issue: $($_[1])`n"}
SendMail $EmailTo $EmailSubject $StrBody
So the breakdown:
Make a mail function
Save the results of your analysis to an array or hashtable
Iterate through your results object and append each result record to the string for your email
Call the email function