【发布时间】:2017-05-26 06:17:04
【问题描述】:
在我的 .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 = New-Object System.Net.NetworkCredential($usercred, $pwcred);
它在$smtp.send($msg)处输出以下错误The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
而且我知道密码是问题所在(至少我很确定),因为如果我手动输入密码,它就可以正常工作。有什么想法吗?
_ 编辑 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 = ""
}
}
【问题讨论】:
-
stackoverflow.com/questions/12460950/… 也有类似的问题,他们建议添加
$smtp.EnableSsl = $true -
嗨 Micky,我也试过了。我将编辑帖子以添加整个发送邮件部分。无论如何,谢谢!
-
如果不使用 SecureString 创建 NetworkCredential,而是将密码以纯文本形式传递给它,会发生什么?
-
如果我这样做,例如
($usercred, "Password123"),那将起作用。 -
你为什么不用
Send-MailMessage?