Can't send email through Powershell - 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)

Related

Run Scripts in Powershell ISE from batch file

I am executing my batch file which opens the Powershell ISE and loads the script but does nothing... I would still need to run manually. Am I missing something here?
BatchFile to call Powershell:
Powershell_ise.exe C:\Users\Desktop\myscript.ps1
That the code am using to monitor the file changes in a folder and to email:
Function Register-Watcher {
param ($folder)
$filter = "logfile.txt" #all files
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$changeAction = [scriptblock]::Create('
# This is the code which will be executed every time a file change is detected
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file $name was $changeType at $timeStamp"
Send-email
')
Register-ObjectEvent $Watcher "Changed" -Action $changeAction
}
Function Send-email{
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "*****#gmail.com"
$Password = "*******"
$to = "*****#gmail.com"
$subject = "Email Subject"
$body = "Insert body text here"
$attachment = "C:\Users\Desktop\AccountMapping.sdl"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)
$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"
}
Register-Watcher "C:\Users\Desktop"

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.

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