Send SQL Query output to email using PowerShell - 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)

Related

Why does attachment do not send with this code?

Why does attachment do not send with this code? how do i remake this code to send email to many recipients?
$EmailTo = "vitaly9oleg#gmail.com"
$EmailFrom = "adm#forceauto.ru"
$Subject = "first letter"
$Body = "Text of the letter"
$SMTPServer = "mail.forceauto.ru"
$filenameAndPath = "C:\1.txt"
$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, 25)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("adm#forceauto.ru", "xxxx");
$SMTPClient.Send($EmailFrom,$EmailTo,$Subject,$Body,$attachment)
I'm not sure how to handle your problem, but perhaps I can still help you with this:
In PowerShell starting from 3.0 you have a cmdlet called Send-MailMessage.
Send-MailMessage -From 'jesfer <jesfer#gmail.com>' -To 'tesrere<tesrere#gmail.com>' -Subject "first letter" -Body "Text of the letter" -SmtpServer "smtp.gmail.com" -UseSsl
Regarding the credentials, it's also a parameter. But using it I'd suggest to us pscredential ob.
Edit: with Credentials
$credentials = new-object Management.Automation.PSCredential “jesfer#gmail.com”, (“s57u5t4” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From 'jesfer <jesfer#gmail.com>' -To 'tesrere<tesrere#gmail.com>' -Subject "first letter" -Body "Text of the letter" -SmtpServer "smtp.gmail.com" -UseSsl -Credential $credentials
Edit 2: with working port
$credentials = new-object Management.Automation.PSCredential “adm#forceauto.ru”, (“xxxxx” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From 'adm <adm#forceauto.ru>' -To 'vitaly9oleg<vitaly9oleg#gmail.com>' -Subject "first letter" -Body "Text of the letter" -SmtpServer "mail.forceauto.ru" -Port 465 -UseSsl -Credential $credentials
Edit 3: with attachment
$credentials = new-object Management.Automation.PSCredential “adm#forceauto.ru”, (“xxxxx” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From 'adm <adm#forceauto.ru>' -To 'vitaly9oleg<vitaly9oleg#gmail.com>' -Subject "first letter" -Body "Text of the letter" -Attachments "C:\1.txt" -SmtpServer "mail.forceauto.ru" -Port 465 -UseSsl -Credential $credentials

Powershell to send mail

Error
New-Object : Cannot find an overload for "PSCredential" and the
argument count: "2". At D:\Scripts\gsend.ps1:12 char:15
Code
#Create Password File (Only need once)
#$Credential = Get-Credential
#$Credential.Password | ConvertFrom-SecureString | Set-Content "D:\scripts\gsendcred.txt"
#Send Email
$EncryptedCredential = "D:\scripts\gsendcred.txt"
$EmailUsername = "me#gmail.com"
$EncryptedPW = Get-Content "D:\scripts\gsendcred.txt"
$EncryptedCredential = ConvertTo-SecureString -String $EncryptedCredential -
AsPlainText -Force
$Credential = New-Object Management.Automation.PSCredential ($EmailUsername,
$EncryptedPW)
$EmailFrom = "me#gmail.com"
$EmailTo = "me#gmail.com"
$EmailSubject = "GSEND Test Subject"
$EmailBody = "Test Body"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = 587
$SMTPSsl = $true
I believe your issue is handling credentials. Here is how I handle the smtp credentials:
$smtpPwd = "password"
$smtpCredentialsUsername = "jdonnelly#xxxxx.com"
$smtpCredentialsPassword = ConvertTo-SecureString -String $smtpPwd -AsPlainText -Force
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential
–ArgumentList $smtpCredentialsUsername, $smtpCredentialsPassword
Then:
$smtp.Credentials = $Credentials
Or if you are using Send-MailMessage store your email credentials locally by running this short script by itself beforehand:
Get-Credential | Export-Clixml C:\fso\myemailcreds.xml
It will prompt you to enter your credentials and then store them locally in (in this case) a folder called fso. Then in any Send-MailMessage cmdlet use the locally stored credentials as follows:
Send-MailMessage -To 'Recipient <recipient#yahoo.com>' -from 'John Donnelly <jdonnelly#xxx.com>'
-cc 'whoever <whoever#xxx.com>' -Subject $subject -Body $body
-BodyAsHtml -smtpserver "smtp.office365.com" -usessl
-Credential (Import-Clixml C:\fso\myemailcreds.xml) -Port 587
You Can use below Powershell script for send mail
Send-MailMessage -To "abc#abc.com" -From "def#abc.com" -Cc "gef#abc.com","hij#abc.com" -Subject Test Mail -BodyAsHtml $htmlbody -SmtpServer "mailhost.abc.com"
where $htmlbody is string variable that contain html.

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)

PowerShell Send Email

See this question's first two answers (have tried both, both generate the below error):
Code (changed necessary pieces):
$EmailFrom = "notifications#somedomain.com"
$EmailTo = "me#earth.com"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Other way (changed necessary pieces):
$credentials = new-object Management.Automation.PSCredential “mailserver#yourcompany.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl
I'm getting this error:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required.
Learn more at
On the first script, the port is explicitly specified, while it's not using PS's built in function (though I haven't had problems with this function in the past).
Thanks!
We send mail with Powershell through Office365. This is what we use (works perfectly). Remember that the user you authenticate with must have "send as"-permissions of the from-address:
$PSEmailServer = "smtp.office365.com"
$credentials = new-object Management.Automation.PSCredential “UserLogonName#domain.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)
$enc = New-Object System.Text.utf8encoding
$from = "FromAddress"
$to = "ToAddress","ToAdress2"
$body = "Test"
$subject = "Test"
Send-MailMessage -port 587 -From $from -BodyAsHtml -Encoding $enc -To $to -Subject $subject -Body $body -UseSsl -Credential $credentials
Try this function to send an email via Gmail:
Function batchsend-mailmessage ($to, $subject, $body, $attachments)
{
$smtpServer = "smtp.gmail.com"
$smtpServerport = "587"
$emailSmtpUser = "TheBatch#gmail.com"
$emailSmtpPass = "PasswordOfTheBatch"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $emailSmtpUser
foreach ($addr in $to)
{
$emailMessage.To.Add($addr)
}
foreach ($attachment in $attachments)
{
$emailMessage.Attachments.Add($attachment)
}
$emailMessage.Subject = $subject
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = $body
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer , $smtpServerport)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser , $emailSmtpPass);
$SMTPClient.Send( $emailMessage )
}
Like this :
batchsend-mailmessage -to $DesAdressesDest -subject $Subject -body $body -attachments $xlsFile