簡體   English   中英

使用powershell發送電子郵件,同時在加密文件中安全地保存密碼

[英]Use powershell to send email while saving your password securely in encrypted file

我找到了類似的線程但沒有解決我的問題。 我正在嘗試使用SMTP服務器發送電子郵件,附件(通過gmail)。 這很容易做到。 我得到的主要錯誤響應是

SMTP服務器需要安全連接或客戶端未經過身份驗證。 服務器響應為:5.5.1需要驗證。“

我認為這與從密碼文件中獲取密碼到Credentials有關

"Password123" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Folder\Password.txt"
$EmailFrom = "emailaddress@gmail.com"
$EmailTo = "otheremailaddress@gmail.com" 
$Subject = "Log file from server" 
$Subject = "Subject" 
$Body = "Here is the log file from the server" 
$File = "C:\Folder\LogFile.txt"
$attachment = New-Object System.Net.Mail.Attachment($File,'text/plain')

$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($emailto)
$mailmessage.Subject = $Subject
$mailmessage.Body = $Body
$mailmessage.Attachments.Add($attachment)

$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 

$username = "emailaddress@gmail.com"
$pass = Get-Content "C:\Folder\Password.txt" | ConvertTo-SecureString -AsPlainText -Force

$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($username, $pass);

$SMTPClient.Send($mailmessage)

我想刪除此代碼的第一行,因為在腳本中輸入密碼永遠不是一個好主意。

如果我將密碼變量更改為以下內容我沒有問題

$pass = "Password123"

我找到的所有其他論壇帖都暗示事情沒有解決我的問題。

同時更改gmails設置以允許從安全性較低的應用程序訪問並不能解決我的問題。

任何幫助將不勝感激

提前致謝。

編輯:

  1. 我有gmail可訪問不太安全的應用程序
  2. 我為gmail做了兩步驗證
  3. 我認為問題在於讀取密碼文件。 這是一種在加密時無法接受文件密碼的情況。 我嘗試使用未加密的密碼,但這對於腳本編寫來說並不是更好

我過去遇到過這個問題 - 我認為Mathias已經提到了一個常見問題 - 注意在不同的憑據下運行(作為調度工作運行),因為解碼依賴於使用用戶的會話信息。 在你的例子中我不太確定的一件事是你為什么要進行后續轉換為純文本 - 否則,下面應該使用你的用戶名和密碼,將其導出到一個文件,然后將其導入為您可以在以后使用的憑證。

$user = "UsernameGoesHere"
$passwordtostore = 'PasswordGoesHere'
$secureStringPWD = $passwordtostore | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPWD | ConvertFrom-SecureString
Set-Content "C:\temp\authenticationfile.cfg" $secureStringText
# Retrieve password
$pwdin = Get-Content "C:\temp\authenticationfile.cfg"
$password = $pwdin | ConvertTo-SecureString
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $user,$password

希望有幫助嗎?

暫無
暫無

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

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