2017-01-30 36 views
1

我想用powershell發郵件。如果我在manualy中鍵入我的憑證,該腳本正常工作。但我想在腳本中提供憑據參數。我的腳本是這樣的:用powershell發郵件

$From = "[email protected]" 
$To = "[email protected]" 
$Cc = "[email protected]" 
$Attachment = "C:\Users\test\test\test.ini" 
$Subject = "Email Subject" 
$Body = "Insert body text here" 
$SMTPServer = "smtp.mail.yahoo.com" 
$SMTPPort = "587" 
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject ` 
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl ` 
-Credential ( 
$MyClearTextUsername=’[email protected]’ 
$MyClearTextPassword=’test123’ 

$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force 

$MyCredentials=New-object System.Management.Automation.PSCredential $MyClearTextPassword,$SecurePassword) -Attachments $Attachment 

回答

1

這裏是你如何創建憑據對象:

在你的情況下使用
$cred = ([pscredential]::new('[email protected]',(ConvertTo-SecureString -String 'test123' -AsPlainText -Force))) 

這樣:

Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject ` 
    -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl ` 
    -Credential $cred -Attachments $Attachment 

我看不出一點在努力適應那到Send-MailMessage,只是之前創建它並引用它。更容易閱讀。

+0

非常感謝! – Tibi

+0

沒問題,如果答案對您有幫助,請將其標記爲答案;)@Tibi – 4c74356b41

+1

標記!直到現在,我都不會讓我。你回答得太快了:D – Tibi