In my .ps1 file I want to execute a job and send the result through email. I want the password to not be readable, so I encrypt it by doing this on beforehand.
$password = read-host -prompt "Enter your Password"
write-host "$password is password"
$secure = ConvertTo-SecureString $password -force -asPlainText
$bytes = ConvertFrom-SecureString $secure
$bytes | out-file .\securepassword.txt
Works just fine so far.
Then I want to use the secured password inside the .ps1, which is where I'm having difficulties. I've tried a bunch of variations, but I think this is my most solid attempt so far:
$usercred = "myemail@gmail.com"
$encryptedpw = Get-Content .\securepassword.txt
$pwcred = $ecryptedpw | ConvertTo-SecureString
When I try to use this in my $smtp.credentials
like this:
$smtp.Credentials = New-Object System.Net.NetworkCredential($usercred, $pwcred);
it outputs the following error The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
at the $smtp.send($msg)
And I know the password is the issue (at least I'm pretty sure), because if I manually type it in - it works just fine. Any ideas?
_ edit 1 _
Below is the whole send-mail part if anyone wonder:
# Send Notification if alert $i is greater then 0
if ($i -gt 0)
{
foreach ($user in $users)
{
$smtpServer = "smtp.gmail.com"
$port = "587"
$smtp.EnableSSL = $true
$smtp = New-Object Net.Mail.SmtpClient($smtpServer, $port)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($usercred, $pwcred);
$msg = New-Object Net.Mail.MailMessage
$msg.To.Add($user)
$msg.From = "myemail@gmail.com"
$msg.Subject = "Environment DiskSpace Report for $titledate"
$msg.IsBodyHTML = $true
$msg.Body = get-content $blablabla
$smtp.Send($msg)
$body = ""
}
}