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.
Related
I want to encrypt the mail using S/MIME standard using powershell. I am able to send mail with attachment(without the encryption from powershell). But when i tried to encrypt it with the following code. It doesn't work as it just remove the file and send the body unencrypted. I am using powershell version 5. For testing purposes I want to use previously generated certificates rather than fetching from somewhere. Please advise on my problem or if there is any better approach.
$email = "*********#gmail.com"
$pass = "*******"
$smtpServer = "smtp.gmail.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$msg.From = "$email"
$msg.To.Add("*****b#***.com")
$msg.BodyEncoding = [system.Text.Encoding]::Unicode
$msg.SubjectEncoding = [system.Text.Encoding]::Unicode
$msg.Headers.Add('MIME-Version','asd')
$msg.Headers.Add("From","**abc**")
$msg.Headers.Add("To","**xyz**")
$msg.Headers.Add("Date","11-11-1111")
$msg.Headers.Add("Subject","asfasdd")
$msg.HeadersEncoding =[system.Text.Encoding]::UTF8
$msg.IsBodyHTML = $true
$msg.Subject = "Test mail from PS"
$msg.Body = "<h2> Test mail from PS </h2>
</br>
Hi there
"
$file= get-item -Path "E:\siddhant\abc.txt"
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass");
$Certname="helloo"
$Cert = New-SelfSignedCertificate -certstorelocation E:\siddhant -dnsname $Certname
$pw = ConvertTo-SecureString -String "Pazzword" -Force -AsPlainText
$thumbprint = $Cert.Thumbprint
$MIMEMessage = New-Object system.Text.StringBuilder
$MIMEMessage.AppendLine("MIME-Version: 1.0") | Out-Null
$MIMEMessage.AppendLine("Content-Type: multipart/mixed; boundary=unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine() | Out-Null
$MIMEMessage.AppendLine("This is a multi-part message in MIME format.") | Out-Null
$MIMEMessage.AppendLine("--unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine("Content-Type: text/plain") | Out-Null
$MIMEMessage.AppendLine("Content-Transfer-Encoding: 7Bit") | Out-Null
$MIMEMessage.AppendLine()
$MIMEMessage.AppendLine($Body) | Out-Null
$MIMEMessage.AppendLine() | Out-Null
$MIMEMessage.AppendLine("--unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine("Content-Type: application/octet-stream; name="+ $file.Name) | Out-Null
$MIMEMessage.AppendLine("Content-Transfer-Encoding: base64") | Out-Null
$MIMEMessage.AppendLine("Content-Disposition: attachment; filename="+ $file.Name) | Out-Null
$MIMEMessage.AppendLine() | Out-Null
[Byte[]] $binaryData = [System.IO.File]::ReadAllBytes($file)
[string] $base64Value = [System.Convert]::ToBase64String($binaryData, 0, $binaryData.Length)
[int] $position = 0
while($position -lt $base64Value.Length)
{
[int] $chunkSize = 100
if (($base64Value.Length - ($position + $chunkSize)) -lt 0)
{
$chunkSize = $base64Value.Length - $position
}
$MIMEMessage.AppendLine($base64Value.Substring($position, $chunkSize))
$MIMEMessage.AppendLine()
$position += $chunkSize;
}
$MIMEMessage.AppendLine("--unique-boundary-1--") | Out-Null
[Byte[]] $BodyBytes = [System.Text.Encoding]::ASCII.GetBytes($MIMEMessage.ToString())
$ContentInfo = New-Object -TypeName System.Security.Cryptography.Pkcs.ContentInfo -
ArgumentList(,$BodyBytes)
$CMSRecipient = New-Object System.Security.Cryptography.Pkcs.CmsRecipient $Cert
$EnvelopedCMS = New-Object System.Security.Cryptography.Pkcs.EnvelopedCms $ContentInfo
$EnvelopedCMS.Encrypt($CMSRecipient)
[Byte[]] $EncryptedBytes = $EnvelopedCMS.Encode()
$MemoryStream = New-Object System.IO.MemoryStream #(,$EncryptedBytes)
$AlternateView = New-Object System.Net.Mail.AlternateView($MemoryStream, "application/pkcs7-mime;
smime-type=enveloped-data;name=smime.p7m")
$msg.AlternateViews.Add($AlternateView)
$smtp.Send($msg)
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)
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)
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
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)