Below is the code snippet used to send mail. which worked until recently and is giving “Failure sending mail." Error. (Version: 5.1.16299.98)
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = " "
$Password = " "
$to = " "
$cc = " "
$subject = "AUTOMATED "
$message = New-Object System.Net.Mail.MailMessage
$message.Subject = $subject
$message.To.Add($to)
$message.Cc.Add($cc)
$message.From = $username
$message.IsBodyHtml = $true
$message.Body =
$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"
The error is:
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At F:\powershell_scripts\xxx.ps1 :88 char:1
+ $smtp.Send($message)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
I can't tell you what the problem is, but I can help you to find out more information about your error!
try {
<your code>
}
catch {
Write-Warning $Error[0].Exception.StackTrace
throw
}
$Error is a special variable in PowerShell that contains a list of the errors that have occurred. Check the documentation for more [/proper] explanation.
$Error[0] is the "most recent" error in the stack.
There are plenty of other properties of the $Error object that you may wish to interrogate for more verbose information... start with
$Error | Get-Member
and go from there.
Hope this helps you get to the bottom of this [and future] issue[s]!
Related
Can someone please help me figure this part out.
#Mail Configuration
$smtpUser = "email#domain.com"
$smtppass = ConvertTo-SecureString "PasswordAsPlainText" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($smtpuser, $smtppass)
$ToAddress = "toaddress#domain.com"
$FromAddress = "send#domain.com"
$SMTPSERVER = "smtp.office365.com"
$SMTPPORT = "587"
$MailParam = #{
To = $ToAddress
From = $FromAddress
Subject = $subject
Body = $Mail
SMTPServer = $SMTPServer
Port = $SMTPPORT
Credential = $pscred
}
#Send Email
$GetChildItem = Get-ChildItem -Path C:\Temp
if ($GetChildItem -ne $Null)
{
Write-Host "Backup Success"
$subject = "$env:COMPUTERNAME SQL Backup Success"
$Mail = "SQL Backup Succeded on the server, please see the attached report for more details"
$attachment = $reportfile
Send-MailMessage #MailParam -BodyAsHtml -usessl
#Exit
}
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$subject = "$env:COMPUTERNAME SQL Backup Failed"
$Mail = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml
#Exit
}
Now I don't think anything is wrong with the code above, I am no expert coder but I can pretty much copy and paste :) and take stuff from there to get it working for me.
The issue with the above code is that when run it, it doesn't work for the 1st time but when you run it again it works fine. The error you get the first time is
Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\Aasim\Desktop\Untitled1.ps1:29 char:26
+ Send-MailMessage #MailParam -BodyAsHtml -usessl
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
I am not sure what the issue is and why it doesn't work only the first time but works every other subsequent time until you close and reopen the script.
Basically I am creating a SQL backup script that backs up databases to our Network Share and then emails me whether it was successful or not. so far the rest of the script works just fine.
In your If and Else blocks, instead of creating a variable $subject, or $Mail, update the hashtable, $MailParam. Also, you seem to be missing the Attachment variable in your Send-MailMessage
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$MailParam.Subject = "$env:COMPUTERNAME SQL Backup Failed"
$MailParam.Body = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml -Attachments $attachment
#Exit
}
I'm working on a project(bonus points) for my intro CyberSec class and I have a cmd script to create a file with info in a usb drive i was trying to use powershell to send the email to myself but keep getting this error:
At D:\mail.ps1:6 char:16
+ $att= $USBDRIVE\file.zip
+ ~~~~~~~~~
Unexpected token '\file.zip' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
here is my powershell script in the entirety.
$USBDRIVE= Get-WMIObject Win32_Volume | ? { $_.label -eq 'ARNOLDHMW' } |
select -expand driveletter
Compress-Archive -Path $USBDRIVE\file -DestinationPath $USBDRIVE\file.zip
$email = "*"
$pass = "*"
$att= $USBDRIVE\file.zip
$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("$email")
$msg.IsBodyHTML = $true
$msg.Subject = "Files Captured"
$msg.Body = "
</br>
Hi there
"
$msg.Attachments.Add($att)
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email",
"$pass");
$smtp.Send($msg)
email and password blanked out for obvious reasons
i'm at a loss here. thanks for the help in advance!
I'm pretty sure the issue you are having is because the value you pass to assign $att isn't a string value. Try assigning the variable as a string instead
$att = "$USBDrive\File.zip"
or better yet
$att = Join-Path -Path $USBDrive -ChildPath "file.zip"
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()
}
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.
How do I send an email containing a binary file using powershell script? Below is my failing best attempt
$to = 'andy.boo#boo.com'
$subject = 'boo'
$file = 'inf.doc'
$from = $to
$filenameAndPath = (Resolve-Path .\$file).ToString()
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = 'smtp.boo.com'
$smtpClient.Send($message)
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\email.ps1:15 char:17
+ $smtpClient.Send <<<< ($message)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
What version of PowerShell? If you're using version 2.0 save yourself the trouble and just use the Send-MailMessage cmdlet.
If version 1.0:
$msg = new-object system.net.mail.MailMessage
$SMTPClient = new-object system.net.mail.smtpClient
$SMTPClient.host = "smtp server"
$msg.From = "Sender"
$msg.To.Add("Recipient")
$msg.Attachments.Add('<fullPathToFile')
$msg.Subject = "subject"
$msg.Body = "MessageBody"
$SMTPClient.Send($Msg)
Found this.. which is a lot better
Send-MailMessage -smtpServer smtp.doe.com -from 'joe#doe.com' -to 'jane#doe.com' -subject 'Testing' -attachment foo.txt