title: Sending email via Powershell using secure password
body: <p>I'm trying to test sending an email but I don't want to just have a plaintext password in my script.</p>
  
  <p>Here's what I have, and this works:</p>
  
  <pre><code>$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 
  </code></pre>
  
  <p>This works.</p>
  
  <p>I followed the advice from <a href="https://stackoverflow.com/questions/6239647/using-powershell-credentials-without-being-prompted-for-a-password">this stackoverflow thread</a>, 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.</p>
  
  <p>I have a secure password I've created by running:</p>
  
  <pre><code>read-host -assecurestring | convertfrom-securestring | out-file C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt
  </code></pre>
  
  <p>But if I replace my $smtpPassword entry with the suggested entry:</p>
  
  <pre><code>$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 
  </code></pre>
  
  <p>Then the email doesn't send anymore. I get the following error:</p>
  
  <blockquote>
    <p>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</p>
  </blockquote>
  
  <p>Any tips? I'd like to run this email script as a scheduled task, but I don't want my password saved in plaintext.</p>