I have found similar threads but none that solve my issue. I am trying to send an email using SMTP server, with attachment (via gmail). That's the easy bit done. The main error response I get is
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."
I think it has to do with getting the password from the password file into the Credentials
"Password123" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Folder\Password.txt"
$EmailFrom = "emailaddress@gmail.com"
$EmailTo = "otheremailaddress@gmail.com"
$Subject = "Log file from server"
$Subject = "Subject"
$Body = "Here is the log file from the server"
$File = "C:\Folder\LogFile.txt"
$attachment = New-Object System.Net.Mail.Attachment($File,'text/plain')
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($emailto)
$mailmessage.Subject = $Subject
$mailmessage.Body = $Body
$mailmessage.Attachments.Add($attachment)
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$username = "emailaddress@gmail.com"
$pass = Get-Content "C:\Folder\Password.txt" | ConvertTo-SecureString -AsPlainText -Force
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($username, $pass);
$SMTPClient.Send($mailmessage)
I want to remove the first line of this code as it's never a good idea to have a password in the script.
If I change the password variable to the following I have no issue
$pass = "Password123"
All the other forum posts I found have suggested things haven't solved my problem.
Also changing gmails settings to allow access from less secure apps doesn't solve my problem.
Any help would greatly be appreciated
Thanks in advance.
EDIT:
- I have gmail accessible for less secure apps
- I have 2 step verification off for gmail
- I believe the issue is reading the password file. It's a case of not being able to accept password from the file when it is encrypted. I tried it with an un-encrypted password but that isn't much better for scripting