Error send mail

Hi,
I’m trying to send, from windows 7, an e-mail using the following code:

$ computers1 = Get-WmiObject-Class Win32_ComputerSystem | out-file “C: \ ProgramData \ list1.txt”
$ computers2 = Get-WmiObject-Class Win32_Product | Select-Object Name -Property> C: \ ProgramData \ list2.txt
$ computers = Get-ChildItem C: \ ProgramData \ list1.txt, C: \ ProgramData \ list2.txt | Get-Content | out-file “C: \ ProgramData \ list.txt”
$EMAILTO = “xxxxx@gmail.com
$Emailfrom = “me@mydomain.com
$Subject = “Test”
$Body = “Test Body”
$SMTPServer = “smtp.gmail.com
filenameAndPath filenameAndPath $ = $ = “C: \ ProgramData \ list.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 System.Net.NetworkCredential = New-Object (“xxxx”, “yyyyy”)
$SmtpClient.Send ($SMTPMessage)

but I get the following error:
Exception while calling “Send” with “1” argument / s: “The SMTP server requires a secure connection or the client was not authenticated. Unknown server response: 5.5.1 Authentication Required. Learn more at”
In line: car 17: 17

  • $ SmtpClient.Send <<<< ($SMTPMessage)
    • CategoryInfo: NotSpecified: (:slight_smile: , MethodInvocationException
    • FullyQualifiedErrorId: DotNetMethodException

Why is that?

This looks a bit off. You’re sending email to xxxxx@gmail.com, from me@mydomain.com, but trying to send it through gmail, logged on as “xxxxx”? Is that xxxxx in the credentials the same as the xxxxx in the To address?

Aside from that, just make sure that the username you’re sending in the credentials is ‘userName@domain’ (where domain might be gmail.com , or maybe something else, depending on how your account is set up.) Gmail’s smtp server expects the @domain part to be there, if I remember correctly.

On a side note, unless you’re using PowerShell 2.0 (which didn’t have a -Port parameter for some silly reason), it might be easier for you to just use the built-in Send-MailMessage cmdlet. Even if you are using PowerShell 2.0, you could use the Send-MailMessage function I have up on the TechNet Gallery (http://gallery.technet.microsoft.com/scriptcenter/Send-MailMessage-3a920a6d). That function’s main reason for existence is to allow inline message attachments, but it also is a handy way of getting a version of Send-MailMessage with a -Port parameter that works on PowerShell 2.0.

Both the cmdlet and the function will take care of things like converting PSCredential objects into the required NetworkCredential objects, disposing of the .NET objects when finished, etc.

Thank you.
With your suggestions now works.
Bye