mail message 支持html,PowerShell的发送,MAILMESSAGE BodyAsHTML错误类型

我创建了一个先进的功能来发送基础上,通过answer proposed Mjolinor电子邮件。但是,我接受HTML代码块时遇到困难。这是抱怨System.String格式,不能转换为System.Management.Automation.SwitchParameter。PowerShell的发送,MAILMESSAGE BodyAsHTML错误类型

对于我的HTML代码我使用的是这里的字符串,使用时像Send-MailMessage -BodyAsHtml $HTML但不是当我尝试它,如下工作正常。我似乎无法弄清楚如何转换它,所以它的工作。

错误:

An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute..

At S:\Test.ps1:168 char:9

+ $EmailParams.keys | Where {$EmailParams.$_ -eq $null} | foreach {$EmailP ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (System.Collecti...tableEnumerator:HashtableEnumerator) [], RuntimeException

+ FullyQualifiedErrorId : BadEnumeration

Failed to send email to [email protected] due to: Cannot convert 'System.String' to the type 'System.Management.Automation.SwitchParameter' required by parameter 'BodyAsHtml'.

代码:

$HTML = @"

 $(if(!$ScriptName){"Test"}else{$ScriptName})

 

 The following has been reported:

$Messages

"@

$EmailParams = @{

To = $To

Cc = $Cc

From = $From

Subject = $Subject

BodyAsHtml = $HTML

Priority = $Priority

SMTPServer = $SMTPserver

Attachments = $Attachment

ErrorAction = 'Stop'

}

$EmailParams.keys | Where {$EmailParams.$_ -eq $null} | foreach {$EmailParams.Remove($_)}

Try { Send-MailMessage @EmailParams }

Catch { "Failed to send email to $($To) due to: $_" }

Finally {}

This person有类似的问题,但这只是来一个System.String为-Body。

谢谢您的帮助。

有两件事情错在这里:

BodyAsHtml是一个布尔($True),所以你需要使用Body提供您的HTML代码。

你不能立即从哈希表中删除的东西。所以你需要2个foreach循环。

完整的答案:

$HTML = @"

 $(if(!$ScriptName){"Test"}else{$ScriptName})

 

 The following has been reported:

$Messages

"@

$EmailParams = @{

To = $To

Cc = $Cc

Bcc = $Bcc

From = $From

Subject = $Subject

Body = $HTML

BodyAsHtml = $True

Priority = $Priority

SMTPServer = $SMTPserver

Attachments = $Attachments

ErrorAction = 'Stop'

}

$list = New-Object System.Collections.ArrayList

foreach ($h in $EmailParams.Keys) {

if ($($EmailParams.Item($h)) -eq $null) {

$null = $list.Add($h)

}

}

foreach ($h in $list) {

$EmailParams.Remove($h)

}

Try {

Send-MailMessage @EmailParams

Write-Verbose "Send-Mail: Sending mail to: $To"

}

Catch {

"Failed to send email to $($To) due to: $_"

}

+1

感谢。我正在考虑直接从powershell发送电子邮件(使用HTML模板),这非常有帮助。我想补充一点,你可以改进最终的解决方案。列表块可以完全删除并替换为这个,干杯:[System.Collections.ArrayList] $ EmailParams.keys | ? {$ EmailParams。$ _ -eq $ null} | %{$ EmailParams.Remove($ _)} –

2016-12-20 00:47:21

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值