Reputation: 11
I'm trying to test sending an email but I don't want to just have a plaintext password in my script.
Here's what I have, and this works:
$SmtpServer = 'smtp.office365.com'
$SmtpUser = '[email protected]'
$smtpPassword = 'Hunter2'
$MailtTo = '[email protected]'
$MailFrom = '[email protected]'
$MailSubject = "Test using $SmtpServer"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -UseSsl -Credential $Credentials
This works.
I followed the advice from this stackoverflow thread, as I'd like this script to run without prompting for credentials (or entering them plaintext), so I can run it as a scheduled task.
I have a secure password I've created by running:
read-host -assecurestring | convertfrom-securestring | out-file C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt
But if I replace my $smtpPassword entry with the suggested entry:
$SmtpServer = 'smtp.office365.com'
$SmtpUser = '[email protected]'
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring
$MailtTo = '[email protected]'
$MailFrom = '[email protected]'
$MailSubject = "Test using $SmtpServer"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -UseSsl -Credential $Credentials
Then the email doesn't send anymore. I get the following error:
Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
Any tips? I'd like to run this email script as a scheduled task, but I don't want my password saved in plaintext.
Upvotes: 0
Views: 6746
Reputation: 11
Coworker helped me realize the $Credentials
object was trying to convert my password back to plaintext. I removed the ConvertTo-SecureSTring -AsPlainText -Force
modifier, and the email sent successfully!
The functioning script:
$SmtpServer = 'smtp.office365.com'
$SmtpUser = '[email protected]'
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring
$MailtTo = '[email protected]'
$MailFrom = '[email protected]'
$MailSubject = "Test using $SmtpServer"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $smtpPassword
Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -UseSsl -Credential $Credentials
Upvotes: 1