How can I embed HTML File in email body - powershell

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)

Related

Sent Mail / PowerShell Credentials

I try to send an email using code based on this example: https://blog.victorsilva.com.uy/credenciales-con-powershell/, but the email is not sending:
$emailSmtpServer = "smtp.mail.yahoo.com"
$emailSmtpServerPort = "587"
$password = Get-Content -Path "C:\Users\USUARIOPC\password2.txt" |
ConvertTo-SecureString -String $password
$credential = New-Object
System.Management.Automation.PsCredential("jrosh.01#yahoo.com", $password)
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "jrosh.01#yahoo.com"
$emailMessage.To.Add( "jrosh.01#yahoo.com" )
$emailMessage.subject = "Notificacion de: $($env:computername)"
$emailMessage.IsBodyHtml = $true
$evento = Get-WinEvent –FilterHashTable #{logname="System"} -MaxEvents 1 |
Where {$_.ID -Match "1020"}
$emailMessage.Body = #"
<H1>Alerta Scope DHCP</H1>
<p>Evento a revisar en: <strong>$($evento.MachineName)</strong>.</p>
<p>Identificador: <strong>$($evento.Id)</strong>.</p>
<p>Fecha / Hora: <strong>$($evento.TimeCreated)</strong>.</p>
<p>Texto: <strong>$($evento.Message)</strong>.</p>
<br>
<H5><i>$(get-date)</i></H5>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,
$emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(
$emailSmtpUser , $credential );
$SMTPClient.Send( $emailMessage )
Write-Host "Correo Enviado..."
From the error messages you submitted it looks like there's a problem with password file. Please make sure that you export your password like this:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\Users\USUARIOPC\password2.txt
Where P#ssword1 is your password.

How to attach excel files in an email using powershell

I have the following select statement that extract data from a SQL Server database table:
$QUERY = "SELECT * FROM Table1"
$DataVariable = Invoke-Sqlcmd -ServerInstance "MyInstance" -Database "MyDB" -Query $QUERY
How can I attach the $DataVariable as an excel file in my email?
I am working on the code below:
$Date = get-date -format "dd-MMM-yyyy"
$Day = $Date.DayOfWeek
$DateTested = $Date
$filename = "MYReport_$(get-date -f yyyy-MM-dd).XLS"
$OutputFile = "\\server\c$\Output\$filename"
I don't seem to go anywhere with this. Can anyone assist please?
Thanks
Your code snippets don't seem to be related to one another
there is no attempt to mail anything
I suggest to save $Datavarable to csv (xlsx is also possible)
this raw example script uses gmail and splatting to fill the parameters
$QUERY = "SELECT * FROM Table1"
$DataVariable = Invoke-Sqlcmd -ServerInstance "MyInstance" -Database "MyDB" -Query $QUERY
$filename = "MYReport_$(get-date -f yyyy-MM-dd).csv"
$OutputFile = "\\server\c$\Output\$filename"
$DataVariable | Export-Csv $OutPutFile -NoTypeInformation
$emailAcc = "youraccount#gmail.com"
$Cred = Get-Credential -UserName $emailAcc -Message "Enter gmail password for $emailAcc"
$MsgParam = #{
From = $emailAcc
To = "recipient#domain.com"
Subject = $filename
Body = 'blah blah sending $filename'
Attachments = $OutPutFile
SmtpServer = "smtp.gmail.com"
}
Send-MailMessage #MsgParam -UseSSL -cred $Cred
I have managed to build the code below and it worked for me !!!!!!!!!!!!!!:
$DataVariable = Invoke-Sqlcmd -ServerInstance $ResultsInstance -Database $ResultsDatabase -Query $SQL
$Date = get-date -format "dd-MMM-yyyy"
$Day = $Date.DayOfWeek
$DateTested = $Date
$filename = "MyReport_$(get-date -f yyyy-MM-dd).csv"
$OutputFile = "\\serverName\c$\Output\$filename"
$DataVariable | Export-csv $OutPutFile -NoTypeInformation
$to = "Support"
$body = "Dear <b><font color=black>$to</b></font> <br>"
$body += "<p>Please find attached report.</p> <br>"
$body += "Kind Regards<br>"
$body += "Dev Team <br>"
$fromaddress = "xyz#xyz.com"
#$toaddress = "x#ytm.com"
$toaddress = "x#ytm.com"
$bccaddress = "x#ytm.com"
$CCaddress = "x#ytm.com"
$Subject = "My weekly report"
$attachment = $OutputFile
$smtpserver = "xyzmail"
####################################
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$message.Priority = [System.Net.Mail.MailPriority]::High
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
if ($DataVariable) {
$smtp.Send($message)
Write-Host "The variable is not null" }

Send SQL Query output to email using PowerShell

I want to send SQL query output to email using PowerShell, how can I do this?
Here is what I have so far:
$query = select name, surname, gender, accountNumber from table1
$Report = Invoke-Sqlcmd -ServerInstance "instance" -Database "db2" -Query $query
$MailUsername = "mail"
$MailPassword = "1234"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "me#yahoo.com" -From "you#yahoo.com" -SmtpServer mail.net -Credential $cred -Subject "weekly Report:" -Body "$Report"
I want to be able to send the report in form of a table or something that looks nice? How can I do that?
My code above is running into errors, can anyone help me please?
Adding an attachment was all I needed, please see below:
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$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)

Can't send email through Powershell

I have been trying to use this script as a simple boolean that checks for a file, and sends a success email, or a failure email. But I cannot for the life of me figure out why it doesn't work.
Any ideas?
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "xxxx#xxxxx.com"
$Password = "xxxxxxx"
$to = "xxx#xxxxx.net"
if ( ([System.Io.fileinfo]'E:\GD Backup Folder\backup\Backup_*.zip').LastWriteTime.Date -ne [datetime]::Today ) {
$message = New-Object System.Net.Mail.MailMessage
$message.subject = "Backup Successful"
$message.body = "Backup was successful."
$message.to.add($to)
$message.from = $username
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}else{
$message = New-Object System.Net.Mail.MailMessage
$message.subject = "Backup Unsuccessful"
$message.body = "Backup was NOT Successful - File Not Found"
$message.to.add($to)
$message.from = $username
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
Send email with attachment using powershell -
$EmailTo = "udit043.ur#gmail.com" // abc#domain.com
$EmailFrom = "udit821#gmail.com" //xyz#gmail.com
$Subject = "zx" //subject
$Body = "Test Body" //body of message
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "G:\abc.jpg" //attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("udit821#gmail.com", "xxxxxxxx"); // xxxxxx-password
$SMTPClient.Send($SMTPMessage)

Attaching to an email in powershell script

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