0

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 = 'fubsygamr@office365.com'
$smtpPassword = 'Hunter2'
$MailtTo = 'fubsygamr@office365.com'
$MailFrom = 'fubsygamr@office365.com'
$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 = 'fubsygamr@office365.com'
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring
$MailtTo = 'fubsygamr@office365.com'
$MailFrom = 'fubsygamr@office365.com'
$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.

Community
  • 1
  • 1
FubsyGamer
  • 11
  • 2
  • 3

1 Answers1

1

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 = 'fubsygamr@office365.com'
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring
$MailtTo = 'fubsygamr@office365.com'
$MailFrom = 'fubsygamr@office365.com'
$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 
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
FubsyGamer
  • 11
  • 2
  • 3