0
votes

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
1
Have you tried turning on less secure apps in google settings google.com/settings/security/lesssecureapps and there is a typo in the network credential part tial($Username, $Password); (I am assuming this happened while pasting code to stackoverflow)ClumsyPuffin
I have done all the necessary settings . this sometimes works when i put a debugger on the error line , wait and then run it . used to work properly before .Me-si
This $smtp.EnableSSL = $true. tial($Username, $Password); makes no sense. Something is missing. Is it a copy-paste error? Are you actually running it in ISE?vonPryz
apologies for the error during code pasting , edited the code aboveMe-si

1 Answers

2
votes

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]!