簡體   English   中英

使用Powershell發送電子郵件

[英]Sending a email with powershell

我想發送帶有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

這是創建憑證對象的方法:

$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沒有任何意義,只需在之前創建它並對其進行引用即可。 更容易閱讀。

如果您使用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

暫無
暫無

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

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