Attaching to an email in powershell script - powershell

I have the following powershell script:
$csv = Import-Csv -Path D:\temp\Audit.csv | Where-Object {$_.PrivateLabelSeqId -eq "602"} | Measure-Object
$Fun = $csv.Count
$mailBody =
#"
There are <b> $Fun </b> available!
"#
Send-MailMessage -Body $mailBody -BodyAsHtml `
-From "mail#mail.com" -To "mailto#mail.com" `
-Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8) `
-Attachment "D:\temp\Audit.csv" `
-SmtpServer "192.0.0.20"
Yet I do not get any email sent out. Without the attachment however, it seems to work just fine. Any ideas on how to resolve this?
Thanks

I encountered the same problem once, i solved it by using System.Net.Mail instead.
$filenameAndPath = (Resolve-Path .\$file).ToString()
$from = 'mail#mail.com'
$to = "mailto#mail.com" `
$Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8)
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = '192.0.0.20'
$smtpClient.Send($message)
To read more about System.Net.Mail.Attachement Class
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

Related

Unable to format Powershell foreach output and attach it to email body and subject

I'm scheduling script if windows scheduled task is disabled from the given list then send email to me with Taskname in email subject and Taskinfo in body.
But I am unable to format email body and add disabled task name in to subject.
Please help me to format email body and add disabled task name to subject.
Here is my script-
$tasknamelist= Import-Csv "C:\Documents\task.csv"
foreach ($task in $tasknamelist) {
$service=Get-ScheduledTask -TaskName "$taskname" | select -ExpandProperty State | Out-String
if ($task.State -eq "Disabled") {
$Body ="$service is not running"
}
else {
Write-Host "$Body Task is enabled" | Out-Null
}
} $Body
$From = "xxx#outlook.com"
$To = "xxx#outlook.com"
$Cc = "xxxx#outlook.com"
#$Attachment = "C:\temp\Some random file.txt"
$Subject = ""
$Body = "$Body"
$computer = $env:computername
$SMTPServer = "outlook.office365.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject "Task Scheduler is disabled on $computer" `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $cred
You have declared $body as an empty vaiable after ending foreach loop. The fixed code is:
$tasknamelist = Import-Csv "C:\Documents\task.csv"
foreach ($task in $tasknamelist) {
$service = Get-ScheduledTask -TaskName "$taskname" | select -ExpandProperty State | Out-String
if ($task.State -eq "Disabled") {
$Body = "$service is not running"
}
else {
Write-Host "$Body Task is enabled" | Out-Null
}
}
$From = "xxx#outlook.com"
$To = "xxx#outlook.com"
$Cc = "xxxx#outlook.com"
#$Attachment = "C:\temp\Some random file.txt"
$Subject = ""
$computer = $env:computername
$SMTPServer = "outlook.office365.com"
$SMTPPort = 587
Send-MailMessage -From $From -to $To -Cc $Cc -Subject "Task Scheduler is disabled on $computer" `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $cred
And you didn't add white space in declaring variable.
$tasknamelist= Import-Csv "C:\Documents\task.csv"
foreach ($task in $tasknamelist)
{
$service=Get-ScheduledTask -TaskName $task
if ($service.State -eq "Disabled")
{
$Body ="$service is not running"
$From = "xxx#outlook.com"
$To = "xxx#outlook.com"
$Cc = "xxxx#outlook.com"
$computer = $env:computername
$Subject = $task + " disabled on " + $computer
$SMTPServer = "outlook.office365.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $cred
}
else
{
Write-Host "$Body Task is enabled" | Out-Null
}
}

Powershell Automated Email

new to the forum, so apologises if this in the wrong area.
I am looking to create a powershell script which emails a list (.txt) file consisting of 200 emails, the text file will be updated aswell with new email addresses. The email body which will be send is a standard (generic) email, nothing specific to each email address.
Is this possible?
This is the script I have so far, but its not sending the email..
$emails = #()
ForEach ($recipient in Get-Content "\\FILE Location")
{
$emails += "$recipient"
}
$to = "TO EMAIL"
$smtp = "SMTP Server"
$from = "FROM EMAIL"
$subject = "Subject"
$body = "EMAIL BODY"
send-MailMessage -SmtpServer $smtp -To $to -Bcc $emails -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high
Thanks in advance
Matt.
In these situations it may be best to create the objects yourself. I would set it up like so:
$smtpServer = "SMTP Server"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtpCredentialsUsername = "blah#blah.com"
$smtpCredentialsPassword = ConvertTo-SecureString -String $smtpPwd -AsPlainText -Force
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList
$smtpCredentialsUsername, $smtpCredentialsPassword
$smtp.Credentials = $Credentials
$msg = new-object Net.Mail.MailMessage
$msg.Body = $body
$msg.Subject = $subject
$msg.From = $from
$msg.To.ADD($to)
$msg.IsBodyHtml = $true
ForEach ($recipient in Get-Content "\\FILE Location")
{
$msg.Bcc.ADD($recipient)
}
$smtp.Send($msg)
$msg.Dispose();

How can I embed HTML File in email body

How can I use powershell to embed an HTML file in email body? This is what I have so far:
##Connect to the data source using the connection details and T-SQL command we provided above, and open the connection
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open()
##Get the results of our command into a DataSet object, and close the connection
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
$dataSet = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet)
$connection.Close()
$body = $TableHeader
$dataSet.Tables | Select-Object -Expand Rows |
Select-Object * -ExcludeProperty Comment, RowError, RowState, Table, ItemArray, HasErrors |
ConvertTo-HTML -head $a –body $body |
Out-File $OutputFile
$ReportLink = "file://serverr/c$/Output/Report.Html"
Write-Output " Reporting"
$MailUsername = "you"
$MailPassword = "your pasword"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "abc#ymail.com" -From "xyz#ymail.com" -SmtpServer Ymail -Credential $cred -Subject " Report:" -Body $ReportLink -BodyAsHtml
I am still new to powershell. Thank you in advance
Assuming the data whichever you want to change to HTML format is in $Result Array
$EmailFrom = ""
$EmailTo = ""
$SMTPServer = ""
$EmailSubject =""
$Report = "<HTML><TITLE>Title</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Heading </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>Row1</B></TD><TD><B>Row2</B></TD><TD><B>Row3</B></TD><TD><B>Row4</B></TD></TR>"
Foreach($Entry in $Result)
{
$Report += "<TR>"
$Report += "<TD>$($Entry.Value1)</TD><TD>$($Entry.Value2)</TD><TD>$($Entry.Value3)</TD><TD align=center>$($Entry.Value4)</TD></TR>"
}
$Report += "</Table></BODY></HTML>"
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = $Report
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer)
$SMTPClient.Send($mailmessage)
I needed to add this script, it works like magic
$message = new-object System.Net.Mail.MailMessage
$message.From = $from
$message.To.Add($to)
$message.CC.Add($CC)
$Subject = " put subject here"
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)

Search for a file that matches a keyword, then attach it to an email

I've written a PowerShell script that searches a folder for a file that matches a keyword eg Japan and then adds the file as an attachment to an email.
The email sends correctly, however the file isn't attached.
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -ErrorAction
SilentlyContinue
$dir = "C:\Users\user\Desktop"
$file = Get-ChildItem -Path $dir | -Filter "$keyword" -Recurse | Select-Object
$keyword = "Japan"
$mailboxdata = (Get-MailboxStatistics | select DisplayName,TotalItemSize,TotalDeletedItemSize, ItemCount, LastLoggedOnUserAccount, LastLogonTime)
$mailboxdata | Export-Csv "$file"
$smtpServer = "192.168.1.100"
$att = New-Object Net.Mail.Attachment($file)
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg.From = "email#mail.com"
$msg.To.Add("email#othermail.com")
$msg.Subject = "Notification from email server"
$msg.Body = "Attached is the email server mailbox report for Japan"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
You've modified a script from another source (that sends Mailbox Statistics from Microsoft Exchange) and you've left in parts of it that you do not need.
$dir = "C:\Users\user\Desktop"
$keyword = "Japan"
$smtpServer = "192.168.1.100"
$file = Get-ChildItem -Path $dir -Filter "*$keyword*" -Recurse
$att = New-Object Net.Mail.Attachment($file)
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg.From = "email#mail.com"
$msg.To.Add("email#othermail.com")
$msg.Subject = "Notification from email server"
$msg.Body = "Attached is the email server mailbox report for Japan"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
I would use Send-MailMessage instead as it's syntax is much easier to use:
$dir = "C:\Users\user\Desktop"
$keyword = "Japan"
$Attachment = Get-ChildItem -Path $dir -Filter "*$keyword*" -Recurse
$From = "email#mail.com"
$To = "email#othermail.com"
$Subject = "Files matching: $keyword"
$Body = "Attached is the file for: $keyword"
$SMTPServer = "192.168.1.100"
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName

Sending multi line of body and multiple attachments

I have two different folders containing two text files, the goal is to send both txt files in an email using PowerShell.
The first file is stored in log and the other one in Error. I found a helpful PowerShell script to do so, however I was not sure how to add both attachments in same email and in the body having two lines for each of the attachments. Below is the script, any help is appreciated:
# Date values to find related log file for the day and hour or the run
$y = Get-Date -format yyyy
$m = Get-Date -format MM
$d = Get-Date -format dd
$h = Get-Date -format 05
# Modify the log path
$LogPath = "C:\Program Files\Logs\"
$LogFile = $LogPath + "Log_" + $y + $m + $d + "_" + $h + "*.txt"
$LogFileName = $LogFile | ? {Test-Path $LogFile} | Get-ChildItem | Where-Object { $_ -is [System.IO.FileInfo] }
$LogPath1 = "C:\Program Files\ERROR\"
$LogFile1 = $LogPath1 + "Log_" + $y + $m + $d + "_" + $h + "*.txt"
$LogFileName1 = $LogFile1 | ? {Test-Path $LogFile} | Get-ChildItem | Where-Object { $_ -is [System.IO.FileInfo] }
$MessageBodyNA = "Email from scheduler. No log file found " + $LogFile
$MessageBodyA = "Email from scheduler. File" + $LogFileName + " found and attached"
$MessageBodyNA1 = "Email from scheduler. No log file found " + $LogFile1
$MessageBodyA1 = "Email from scheduler. File(s) " + $LogFileName1 + " found and attached"
$FromAddress = "test#gmail.com"
$ToAddress = "test1#gmail.com"
$Subject = "test"
$SMTPserver = "SMTPServerName.com"
if ( $LogFileName | Where-Object { $_ -is [System.IO.FileInfo] })
{
send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject -body $MessageBodyA -smtpServer $SMTPserver -Attachments $LogFileName
}
else
{
send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject -body $MessageBodyNA -smtpServer $SMTPserver
}
if ( $LogFileName1 | Where-Object { $_ -is [System.IO.FileInfo] })
{
send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject -body $MessageBodyA1 -smtpServer $SMTPserver -Attachments $LogFileName1
}
else
{
send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject -body $MessageBodyNA1 -smtpServer $SMTPserver
}
When in doubt, read the documentation. The -Attachment parameter accepts a string array, so you can attach multiple files like this:
Send-MailMessage -From $FromAddress -To $ToAddress -Subject $Subject `
-Body $MessageBodyA -SmtpServer $SMTPserver `
-Attachments $LogFileName, $logFileName1
A multiline body can easily be created by using a multiline string:
$MessageBody = #"
This is line 1.
This is line 2.
"#
or by concatenating multiple lines:
$line1 = "This is line 1."
$line2 = "This is line 2."
$MessageBody = "$line1`n`n$line2"
This shows how to attach multiple files and multiple lines in mail body (please note that I didn't tested this)
function sendMail{
#SMTP server name and other mail parameters
$smtpServer = "smtp.bethanie.com.au"
$OFS = "`r`n`r`n"
$a = get-date
$SourceDir = "C:\Source\"
$DestDir = "C:\Dest\"
$files = get-childitem $SourceDir | where name -like "*.txt"
$attachments = #()
$msgFrom = "abc#abc.com"
$msgTo = "abc#abc.com"
$msgsubject = "Automated Task(" + $a + " )"
$msgBody = "This is an automated mail" + $OFS + "Check the attached file"
# Attach files of specific types
foreach($file in $files){
$filename = [system.io.path]::GetFileName($file.FullName)
$attachments += $file.fullname
}
Send-MailMessage -to $msgTo -From $msgFrom -SmtpServer $smtpServer -Subject $msgsubject -BodyAsHtml $msgBody -Attachments $attachments
}
#Calling function
sendMail