我想发送一封包含powershell的电子邮件。如果我手动输入我的凭证,该脚本可以正常工作。但我想在脚本中提供凭证参数。我的脚本看起来像这样:
$From = "test@yahoo.de"
$To = "test2@yahoo.de"
$Cc = "test@yahoo.de"
$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=’test@yahoo.de’
$MyClearTextPassword=’test123’
$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force
$MyCredentials=New-object System.Management.Automation.PSCredential $MyClearTextPassword,$SecurePassword) -Attachments $Attachment
答案 0 :(得分:2)
以下是如何创建凭据对象:
$cred = ([pscredential]::new('test@yahoo.de',(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
,只需在之前创建并引用它。更容易阅读。
答案 1 :(得分:1)
如果您使用Office365发送电子邮件,则可能需要尝试以下操作:
# Sending an email from PowerShell 5.1 script through outlook.office365.com
#
# 1. Create an encrypted password file
# PS > Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath <passwordfile>
# This will prompt you for a password, encrypt and save in <passwordfile>
# 2. Obtain Outlook Office365 SMTP server name.
# Go to your ISP and find the value of the MX record. For example <yourdomain>.mail.protection.outlook.com
# 3. If after running the script you get this error:
# Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP [X.X.X.X].
# You will need to delist your IP by going here: https://sender.office.com/
# Note: Removing you IP from the block list could take up to 30 minutes.
#
$User = "<SMPT loging username>"
$PasswordFile = "<passwordfile>"
$SMTPCredentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString)
$EmailTo = "<to email address>"
$EmailFrom = "<from email address>"
$Subject = "<email subject>"
$Body = "<email body>"
$SMTPServer = "<Outlook STMP Server from MX record>"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 25 -Credential $SMTPCredentials -UseSsl