Why my Powershell script doesnt work? - email

I have created script for checking if VPN connection is disconnected and try to reconnect. Its also sending emails, when
1) cant ping VPN server with remote LAN address
2) VPN connection fails
3) VPN connection is established.
First email is sent and received properly, but Powershell gives error, when it have to send another email.
Code inside vpn.ps1 file:
$ip = "*.*.*.*"
$result = Get-WmiObject -Query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip'"
if($result.StatusCode -eq 0) {
} else {
Start-Sleep -s 15
$EmailFrom = "*#*.*"
$EmailTo = "*#*.*"
$Subject = "###"
$Body = "#####################################################"
$SMTPServer = "*.*.*.*"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, ***)
#$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("*#*.*", "*************");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
rasdial.exe ********** /DISCONNECT
rasdial.exe ******** ****** ******
Start-Sleep -Seconds 15
$ip = "*.*.*.*"
$result = Get-WmiObject -Query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip'"
if ($result.StatusCode -eq 0) {
$EmailFrom = "*#*.*"
$EmailTo = "*#*.*"
$Subject = "########"
$Body = "####################################"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
} else {
Start-Sleep -s 15
$EmailFrom = "*#*.*"
$EmailTo = "*#*.*"
$Subject = "################"
$Body = "##########################################"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
}
Log when running:
PS Microsoft.PowerShell.Core\FileSystem::***********> *******\vpn.ps1
#FIRST EMAIL SENT
No connections
Command completed successfully.
Connecting to *********...
Verifying username and password...
Registering your computer on the network...
Successfully connected to ******.
Command completed successfully.
Exception calling "Send" with "4" argument(s): "Failure sending mail."
At \\tsclient\C\New folder\vpn.ps1:26 char:9
+ $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
PS Microsoft.PowerShell.Core\FileSystem::******
I have sensored usernames, passwords, addresses etc. What is wrong with my script?

Your $SMTPClient object isnt declared in the else block.
You need an instance of that object inside of the block, where you use it, or declare it outside, to have one global $SMTPClient object, which is present in the blocks. You also have to fill the $SMTPClient.Credentials.
Best solution will be, to declare both before the if Statement in line 3.
Update
Move these lines
$SMTPServer = "*.*.*.*"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, ***)
#$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("*#*.*", "*************");
out of those if .. else ..
Just move it to line 2, right before the if block.

Related

Is there any way to send email to users with attachment using SharePoint/office 365?

I have created a PowerShell script to send email with attachment getting the below error. Is there another way or how to resolve the below issue ?
Error:
Exception: Exception calling "Send" with "1" argument(s): "Error in processing. The server response was: 5.7.3 STARTTLS is required to send mail [BM1PR0101CA0039.INDPRD01.
PROD.OUTLOOK.COM]"
PowerShell Script:
function send-emailwithattachment( [string] $subject, [string] $body, [string] $FilesPath )
{
$smtpServer = "smtp.office365.com"
$msg = new-object Net.Mail.MailMessage
$to= "raj#qwert.com"
$cc= "Raman#qwert.com", "rama#qwert.com"
$emailSmtpUser="nanda#qwert.com"
$emailSmtpPass="ZXCCXZ#ASD"
#Change port number for SSL to 587
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
#Uncomment Next line for SSL
#$smtp.EnableSsl = $true
#From Address
$msg.From = "nanda#qwert.com"
#To Address, Copy the below line for multiple recipients
$msg.To.Add($to)
$msg.Cc.Add($cc)
#Message Subject
$msg.Subject = $subject
$msg.Body = $body
#$attachment = New-Object System.Net.Mail.Attachment –ArgumentList $FilesPath
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList D:\ListData.csv
$msg.Attachments.Add($attachment)
$smtp.EnableSsl = $False
$smtp.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass,"qwert.com" );
$smtp.Send($msg)
$msg.Dispose();
}

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 send email with PowerShell

I'd like to send email from PowerShell,
so I use this command:
$EmailFrom = "customer#yahoo.com"
$EmailTo = "receiver#ymail.com"
$Subject = "today date"
$Body = "TODAY SYSTEM DATE=01/04/2016 SYSTEM TIME=11:32:05.50"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("customer#yahoo.com", "password")
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
This command didn't work for Yahoo mail or Outlook mail, but works for my Gmail.
Is there anything wrong that I have done?
Following code snippet really works for me:
$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";
function Send-ToEmail([string]$email, [string]$attachmentpath){
$message = new-object Net.Mail.MailMessage;
$message.From = "YourName#gmail.com";
$message.To.Add($email);
$message.Subject = "subject text here...";
$message.Body = "body text here...";
$attachment = New-Object Net.Mail.Attachment($attachmentpath);
$message.Attachments.Add($attachment);
$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message);
write-host "Mail Sent" ;
$attachment.Dispose();
}
Send-ToEmail -email "reciever#gmail.com" -attachmentpath $path;
I use this:
Send-MailMessage -To hi#abc.com -from hi2#abc.com -Subject 'hi' -SmtpServer 10.1.1.1
You can simply use the Gmail smtp.
Following is The powershell code to send a gmail message with an Attachment:
$Message = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", 587)
$smtp.Credentials = New-Object System.Net.NetworkCredential("From#gmail.com", "password");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "From#gmail.com"
$Message.To.Add("To#gmail.com")
$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
On the sender Google Account (From#gmail.com),
Make sure you have Turned ON Access for less-secure apps option,
from google Account Security Dashboard.
Finally, Save this Script As mail.ps1
To invoke the above Script Simple run below on Command Prompt or batch file:
Powershell.exe -executionpolicy remotesigned -File mail.ps1
By Default, For sending Large Attachments Timeout is Around 100 seconds or so.
In this script, it is increased to Around 5 or 6 minutes
Sometimes you may need to set the EnableSsl to false (in this case the message will be sent unencrypted over the network)

Sending mail Power Shell 4

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.

Accessing Mapped Network Drive Fails In Scheduled Task

I have the following powershell script which checks a drive to see if it is low on space, and if so stops sabnzbd downloads and sends me an email:
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='B:'" | Select-Object FreeSpace
$gb =$disk.FreeSpace /1073741824
if($gb -lt 3)
{
$wc = New-Object system.Net.WebClient;
$smsResult = $wc.downloadString("http://localhost:8080/sabnzbd/api?mode=pause&apikey=XXXXXXX")
$EmailFrom = "XXXXXXX"
$EmailTo = "XXXXXXX"
$Subject = "NAS out of space <eom>"
$Body = ""
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("XXXXXXX", "XXXXXXX");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
This works perfectly when running in powershell through the console or ISE, but when I setup a scheduled task the WMI query returns the drive size as 0. I do not get any errors and task scheduler says the task completed successfully. I run the task with elevated privileges as my administrator account. Have also tried to run as SYSTEM without any luck. I have seen other people ask similar questions a long time ago, but it does not seem like they got any answers.
Working off of andyb's comment I was able to fix this by mapping and unmapping the drive explicitly so that Powershell can use it.
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("K:", "\\192.0.0.0\NAS", $false, "192.0.0.0\NASAdmin", "xxxxxx")
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='K:'" | Select-Object FreeSpace
$gb =$disk.FreeSpace /1073741824
$gb>E:\test.txt
if($gb -lt 3)
{
$wc = New-Object system.Net.WebClient;
$smsResult = $wc.downloadString("http://localhost:8080/sabnzbd/api?mode=pause&apikey=xxxxxx")
$EmailFrom = "xxxxxx"
$EmailTo = "xxxxxx"
$Subject = "NAS out of space <eom>"
$Body = ""
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxxxx", "xxxxxx");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
Start-Sleep 5
$net.RemoveNetworkDrive("K:");