unable to set up send-email function as desired - powershell

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)
#>

Related

Sending emails using multiple attachments using powershell script

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)"
}
}

send-mailmessage to send different attachments to different recipients

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.

powershell - get file, parse it and if "value=" < X then function sendMail

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

How to accept confirmation Automatically in PowerShell for Outlook

How to accept confirmation Automatically in PowerShell for Outlook
I have script for Export attachments from email from Outlook - see next
It works correctly on one PC, but on another PC is there a problem:
Outlook gives message and wants answer:
Permit Denny Help
If I manually click on Permit or Denny it works correctly. I want to automate it.
Can you give me some suggestion how to do it in PowerShell?
I have tried to set Outlook to not give this message but I didn’t success.
My script:
# <-- Script --------->
# script works with outlook Inbox folder
# check if email have attachments with ".txt" and save those attachments to $filepath
# path for exported files - attachments
$filepath = "d:\Exported_files\"
# create object outlook
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace("MAPI")
# $f - folder „dorucena posta“ 6 - Inbox
$f = $n.GetDefaultFolder(6) # 6 - Inbox
# select newest 10 emails, from it olny this one with attachments
$f.Items| select -last 10| Where {$_.Attachments}| foreach {
# process only unreaded mail
if($_.unread -eq $True) {
# processed mail set as read, not to process this mail again next day
$_.unread = $False
$SenderName = $_.SenderName
Write-Host "Email from: ", $SenderName
# process all attachments
$_.attachments|foreach {
$a = $_.filename
If ($a.Contains(".txt")) {
Write-Host $SenderName," ", $a
# copy *.txt attachments to folder $filepath
$_.saveasfile((Join-Path $filepath "$a"))
}
}
}
}
Write-Host "Finish"
# <------ End Script ---------------------------------->
I found that security prompt is generate on line
" $SenderName = $_.SenderName "
Realy I dont need to use SenderName and I deleted this line.
Now script works OK without any message.

Expressions are only allowed as the first element of a pipeline

I'm new at writing in powershell but this is what I'm trying to accomplish.
I want to compare the dates of the two excel files to determine if one is newer than the other.
I want to convert a file from csv to xls on a computer that doesn't have excel. Only if the statement above is true, the initial xls file was copied already.
I want to copy the newly converted xls file to another location
If the file is already open it will fail to copy so I want to send out an email alert on success or failure of this operation.
Here is the script that I'm having issues with. The error is "Expressions are only allowed as the first element of a pipeline." I know it's to do with the email operation but I'm at a loss as to how to write this out manually with all those variables included. There are probably more errors but I'm not seeing them now. Thanks for any help, I appreciate it!
$CSV = "C:filename.csv"
$LocalXLS = "C:\filename.xls"
$RemoteXLS = "D:\filename.xls"
$LocalDate = (Get-Item $LocalXLS).LASTWRITETIME
$RemoteDate = (Get-Item $RemoteXLS).LASTWRITETIME
$convert = "D:\CSV Converter\csvcnv.exe"
if ($LocalDate -eq $RemoteDate) {break}
else {
& $convert $CSV $LocalXLS
$FromAddress = "email#address.com"
$ToAddress = "email#address.com"
$MessageSubject = "vague subject"
$SendingServer = "mail.mail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SendEmailSuccess = $MessageBody = "The copy completed successfully!" | New-Object System.Net.Mail.SMTPClient mail.mail.com $SMTPMessage
$RenamedXLS = {$_.BaseName+(Get-Date -f yyyy-MM-dd)+$_.Extension}
Rename-Item -path $RemoteXLS -newname $RenamedXLS -force -erroraction silentlycontinue
If (!$error)
{ $SendEmailSuccess | copy-item $LocalXLS -destination $RemoteXLS -force }
Else
{$MessageBody = "The copy failed, please make sure the file is closed." | $SMTPClient.Send($SMTPMessage)}
}
You get this error when you are trying to execute an independent block of code from within a pipeline chain.
Just as a different example, imagine this code using jQuery:
$("div").not(".main").console.log(this)
Each dot (.) will chain the array into the next function. In the above function this breaks with console because it's not meant to have any values piped in. If we want to break from our chaining to execute some code (perhaps on objects in the chain - we can do so with each like this:
$("div").not(".main").each(function() {console.log(this)})
The solution is powershell is identical. If you want to run a script against each item in your chain individually, you can use ForEach-Object or it's alias (%).
Imagine you have the following function in Powershell:
$settings | ?{$_.Key -eq 'Environment' } | $_.Value = "Prod"
The last line cannot be executed because it is a script, but we can fix that with ForEach like this:
$settings | ?{$_.Key -eq 'Environment' } | %{ $_.Value = "Prod" }
This error basically happens when you use an expression on the receiving side of the pipeline when it cannot receive the objects from the pipeline.
You would get the error if you do something like this:
$a="test" | $a
or even this:
"test" | $a
I don't know why are trying to pipe everywhere. I would recommend you to learn basics about Powershell pipelining. You are approaching it wrong. Also, I think you can refer to the link below to see how to send mail, should be straight forward without the complications that you have added with the pipes : http://www.searchmarked.com/windows/how-to-send-an-email-using-a-windows-powershell-script.php