Sending mail Power Shell 4 - powershell

Good Day! Help please, use this script here:
$file = "C:\Reports\Log_1.txt"
$FileExists = Test-Path $file
If ($FileExists -eq "False") {
Write-Host "sending mail"
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = New-Object System.Net.Mail.MailAddress("test#gmail.com")
$mail.To.Add("test#gmail.com")
$mail.Subject = "report";
$mail.Body = get-content $file
$smtp = New-Object System.Net.Mail.SmtpClient
$smtp.host = "smtp.domen.com"
$smtp.port="25"
$Credentials = new-object System.Net.networkCredential
$Credentials.domain = "smtp.domen.com"
$Credentials.UserName = "test#gmail.com"
$Credentials.Password = "rgrthbdgfhytju"
$smtp.Credentials = $Credentials
$smtp.Send($mail)
}
# else {
#Write-Host "File $file not found"
#}
I get two errors trying to connect the two mail servers.
In the first case, the connection error and the second authentication error:
error 1 (gmail.com): Exception calling with this 1 argument This operation has timed out.
error 2 (corporate post): Exception calling with this 1 argument Failure sending mail.
Sorry,I can not insert a picture of the limitations.

Related

Powershell RDS CAL email Report

I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)

Power Shell: If condition variable comparison not working

I have a piece of code comparing two values, and if the condition is satisfied it sends out an email. But it is not working, help is appreciated.
code:
$filesize = Get-ChildItem $filename | Select-Object Length | Format-Wide
$filesize
$num=1265
$num
if("$filesize" -gt "$num")
{
$SMTPServer = "10.20.19.94"
$SMTPPort = 25
$username = "vcenter#somosadc.com"
#Define the receiver of the report
$to = "jeevan.m2#hcl.com"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = new-object Net.Mail.Attachment($filename)
$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 = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
output:
1262
1265
Mail Sent
Why is it sending email if $filesize=1262 is less than $num=1265. It is killing me.
Because you're not comparing two numbers, you're comparing two strings.
Remove the Format-Wide command from the first pipeline, and remove the quotes around the arguments in your if condition:
$filesize = Get-ChildItem $filename | Select-Object Length
$num = 1265
if($filesize.Length -gt $num) {
<# ... #>
}

New to error handling

The path that I have set is not valid, when the copy fails I want to send an email to someone. If there is no error then send an email stating the copy was successful.
Current it doesnt give me an error and it doesnt send an email. I know that the email part is correct and confirmed it does work.
My script block.
try
{
Copy-Item -path "\\main-
4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
}
catch
{
$from = "alerts#domain.com"
$to = "me#domain.com"
$subject = "Copy Failed"
$body = "The Copy failed to complete, please make sure the servers rebooted"
$msg = "$file"
$Attachment = "$file"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("mail.domain.com")
$msg.From = $From
$msg.To.Add($To)
if($Attachment.Length -gt 1)
{
$msg.Attachments.Add($Attachment)
}
$msg.Subject = $Subject
$msg.IsBodyHtml = $true
$msg.Body = $Body
$smtp.Send($msg)
}
How about this as a solution for sending an email for both failure and success without duplicating the email send code:
$Status = 'Succeeded'
try{
Copy-Item -path "\\main-4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
}catch{
$Status = 'Failed'
}finally{
$from = "alerts#domain.com"
$to = "me#domain.com"
$subject = "Copy $Status"
$body = "The Copy $Status"
If ($Status = 'Failed') {$body += ", please make sure the server is rebooted" }
$Attachment = "$file"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("mail.domain.com")
$msg.From = $From
$msg.To.Add($To)
if($Attachment.Length -gt 1){
$msg.Attachments.Add($Attachment)
}
$msg.Subject = $Subject
$msg.IsBodyHtml = $true
$msg.Body = $Body
$smtp.Send($msg)
}
You don't really need to use a Finally block, but it does create a nice code block to make explicit what the email functionality belongs to.

Unable to Send Outlook Email via Powershell

I can create an email and display it with my script, but for some reason it doesn't send and I receive the following error. Am I missing something, maybe there's a permissions issue?
Exception calling "Send" with "0" argument(s): "Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))"At C:\TEMP\Scripts\PowerShell\Outlook EMail Creation\TestEMailSend.ps1:27 char:5
+ $mail.Send()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
My code:
$global:UserReportsToEmail = "my.email#domain.com"
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "$global:UserReportsToEmail"
$mail.cc = "EMAIL#domain.com"
$mail.Subject = "mySubject"
$mail.HTMLBody =
"<font color ='blue'><b>TESTING STUFFFF!</b></font><br>
Text on a new line $UserID"
$mail.Send()
$inspector = $mail.GetInspector
$inspector.Display()
According to a few of the Microsoft sites (e.g. https://social.msdn.microsoft.com/Forums/en-US/80c66a08-66ee-4ab6-b629-6b1e70143eb0/operation-aborted-exception-from-hresult-0x80004004-eabort-outlook-appointment?forum=outlookdev ) this is due to 'object model guard'. A security feature to prevent automated programs from doing stuff like auto-emailing out viruses and stuff from the background.
You probably already worked this out. Posting this here so that others like myself can more quickly and easily understand why its not working.
you can use the Send-MailMessage CmdLets : https://technet.microsoft.com/en-us/library/hh849925.aspx
then when i need more controls and dispose functionnality i use System.Net.Mail.SmtpClient
try
{
$emailCredentials = Import-Clixml "C:\testMail\credentials.clixml"
$recipients = #("user#mail.com", "user2#mail.com", "user3#mail.com")
$attachments = #("C:\testMail\file.txt", ""C:\testMail\file2.txt", "C:\testMail\file3.txt")
# create mail and server objects
$message = New-Object -TypeName System.Net.Mail.MailMessage
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient($buildInfoData.BuildReports.Mail.Server)
# build message
$recipients | % { $message.To.Add($_) }
$message.Subject = $subject
$message.From = New-Object System.Net.Mail.MailAddress($emailCredentials.UserName)
$message.Body = $mailHtml
$message.IsBodyHtml = $true
$attachments | % { $message.Attachments.Add($(New-Object System.Net.Mail.Attachment $_)) }
# build SMTP server
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient(smtp.googlemail.com)
$smtp.Port = 572
$smtp.Credentials = [System.Net.ICredentialsByHost]$emailCredentials
$smtp.EnableSsl = $true
# send message
$smtp.Send($message)
Write-Host "Email message sent"
}
catch
{
Write-Warning "$($_.Exception | Select Message, Source, ErrorCode, InnerException, StackTrace | Format-List | Out-String)"
}
finally
{
Write-Verbose "Disposing Smtp Object"
$message.Dispose()
$smtp.Dispose()
}

How to attach a file to an email with PowerShell

I have written a PowerShell script that will create an email, however I can't seem to attach a file. The file does exist and PowerShell can open it, Could anyone tell me what I'm doing wrong?
$ol = New-Object -comObject Outlook.Application
$message = $ol.CreateItem(0)
$message.Recipients.Add("Deployment")
$message.Subject = "Website deployment"
$message.Body = "See attached file for the updates made to the website`r`n`r`nWarm Regards`r`nLuke"
# Attach a file this doesn't work
$file = "K:\Deploy-log.csv"
$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
If you are on PowerShell 2.0, just use the built-in cmdlet Send-MailMessage:
C:\PS>Send-MailMessage -from "User01 <user01#example.com>" `
-to "User02 <user02#example.com>", `
"User03 <user03#example.com>" `
-subject "Sending the Attachment" `
-body "Forgot to send the attachment. Sending now." `
-Attachment "data.csv" -smtpServer smtp.fabrikam.com
If you copy/paste this watch out for the extra space added after the backtick. PowerShell doesn't like it.
I got the above to work by removing the line
$attachment = new-object System.Net.Mail.Attachment $file
and changing
$message.Attachments.Add($attachment)
to
$message.Attachments.Add($file)
While the solution provided by #Keith Hill would be better, even with a lot of goggling I couldn't get it to work.
This worked for me using powershell-
Define Variables:
$fromaddress = "donotreply#pd.com"
$toaddress = "test#pd.com"
$Subject = "Test message"
$body = "Please find attached - test"
$attachment = "C:\temp\test.csv"
$smtpserver = "mail.pd.com"
Use the variables in the script:
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$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)
You can use send-mailmessage or system.net.mail.MailMessage to accomplish it. Interestingly, there is a significant execution time difference between the two approaches. You can use measure-command to observe the execution time of the commands.
I have experienced such problem, (windows 10 / PS 5.1)
My SMTP is not authentified or secure ...
I have to finish by this line "MyAttacheObject.Dispose()"
... / and finally that's work :!
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$attach.Dispose()
this is my code with two attachments :
# Email configuration NO AUTH NO SECURE
$emailHost = "smtp.bot.com"
$emailUser = ""
$emailPass = ""
$emailFrom = "myemail#bot.com"
$emailsTo=#("toyoumylove#bot.com","toyoumybad#bot.com")
$emailSubject = $title
$emailbody=$body
$attachment1 = #($PATh+$outFile)
$attachment2 = #($PATh+$inFile)
#End of parameters
$msg = New-Object System.Net.Mail.MailMessage
$msg.from = ($emailFrom)
foreach ($d in $emailsTo) {
$msg.to.add($d)
}
$msg.Subject = $emailSubject
$msg.Body = $emailbody
$msg.isBodyhtml = $true
$att = new-object System.Net.Mail.Attachment($attachment1)
$msg.Attachments.add($att)
$att = new-object System.Net.Mail.Attachment($attachment2)
$msg.Attachments.add($att)
$smtp = New-Object System.Net.Mail.SmtpClient $emailHost
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
$smtp.send($msg)
$att.Dispose()
"yourpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\Password.txt"
# The above command will encrypt the password you need to run this command only one time
# 1.Sign in to your work or school account, go to the My Account page, and select Security info.
2.Select Add method, choose App password from the list, and then select Add.
3.Enter a name for the app password, and then select Next. it will give password
# you should use this password in above mentioned command
$User = "mymail#company.net"
$File = "C:\Users\username\Desktop\Mail\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "mymail#company.net"
$EmailFrom = "mymail#company.net"
$Subject = "SERVICE STOPPED"
$Body = "SERVICE STOPPED PFA Document to get more details."
$SMTPServer = "smtp.office365.com"
$filenameAndPath = "C:\Users\username\Desktop\new.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, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
I needed to drop the "-AsPlainText -Force"
$emailCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $emailUser, (Get-Content $emailPasswordFile | ConvertTo-SecureString)