簡體   English   中英

如何在smtp憑證中使用加密的安全密碼

[英]How can I use encrypted secure password in smtp credentials

在我的.ps1文件中,我要執行作業並通過電子郵件發送結果。 我希望密碼不可讀,所以我事先進行了加密。

$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

到目前為止一切正常。

然后,我想在.ps1內使用安全密碼,這是我遇到的困難。 我已經嘗試了很多變化,但是我認為這是迄今為止我最扎實的嘗試:

 $usercred = "myemail@gmail.com"
 $encryptedpw = Get-Content .\securepassword.txt
 $pwcred = $ecryptedpw | ConvertTo-SecureString

當我嘗試在$smtp.credentials使用此$smtp.credentials如下所示:

$smtp.Credentials = New-Object System.Net.NetworkCredential($usercred, $pwcred);

它輸出以下錯誤The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. $smtp.send($msg)

而且我知道密碼是問題所在(至少我很確定),因為如果手動輸入密碼,它就可以正常工作。 有任何想法嗎?

_編輯1 _

如果有人懷疑,以下是整個發送郵件部分:

# 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 = "" 
    } 
  } 

感謝這里的一些投入,我得以制定出解決方案。 我認為另一個因素也起作用。

1)我從另一台機器加密了密碼,我顯然不應該這樣做。 我注意到加密的結果是根據進行加密的計算機而有所區別的(有人可以隨意解釋這一點)。

2)我最終得到的代碼如下:

$usercred = "myemail@gmail.com" $encryptedpw = Get-Content .\\securepassword.txt $password = ConvertTo-SecureString -String $encryptedpw

接着

$smtp.Credentials = New-Object System.Net.NetworkCredential($usercred, $password);

根據此鏈接的答案,您可以嘗試以下操作:

$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $FileWhereYouIsStored | ConvertTo-SecureString)
$smtp.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);

希望能有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM