2017-04-04 159 views
0

我想测试发送电子邮件,但我不想在脚本中只有明文密码。使用安全密码通过Powershell发送电子邮件

这里是我有,这一点也适用:

$SmtpServer = 'smtp.office365.com' 
$SmtpUser = '[email protected]' 
$smtpPassword = 'Hunter2' 
$MailtTo = '[email protected]' 
$MailFrom = '[email protected]' 
$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 

这工作。

我遵循this stackoverflow thread的建议,因为我希望此脚本在没有提示凭据(或输入明文)的情况下运行,因此我可以将其作为计划任务运行。

我有我已经运行时创建一个安全密码:

read-host -assecurestring | convertfrom-securestring | out-file C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt 

但如果我代替我,用建议的条目$ smtpPassword项:

$SmtpServer = 'smtp.office365.com' 
$SmtpUser = '[email protected]' 
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring 
$MailtTo = '[email protected]' 
$MailFrom = '[email protected]' 
$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 

然后电子邮件不发送了。我收到以下错误:

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

任何提示?我想将此电子邮件脚本作为计划任务运行,但我不希望以明文形式保存密码。

回答

1

同事帮我意识到$Credentials对象试图将我的密码转换回明文。我删除了ConvertTo-SecureSTring -AsPlainText -Force修饰符,并且发送邮件成功!

运作的脚本:

$SmtpServer = 'smtp.office365.com' 
$SmtpUser = '[email protected]' 
$smtpPassword = cat C:\Users\FubsyGamr\Documents\mysecurestring_fubsygamr.txt | convertto-securestring 
$MailtTo = '[email protected]' 
$MailFrom = '[email protected]' 
$MailSubject = "Test using $SmtpServer" 
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $smtpPassword 
Send-MailMessage -To "$MailtTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -UseSsl -Credential $Credentials