PowerShell中如何将文件内容插入HTML邮件正文并解析变量
问题解决:PowerShell邮件API中变量解析与JSON格式错误
问题根源分析
- 变量不解析:初始脚本用单引号包裹JSON字符串,PowerShell中单引号是字面量字符串,内部的
$pass变量不会被替换,因此邮件正文显示的是变量名而非实际密码。 - JSON格式错误:修改后直接在单引号中嵌套双引号引用
$pass,导致JSON结构被破坏——JSON要求字符串必须用双引号包裹,手动拼接时的引号嵌套会引发解析失败。
解决方案
方案1:双引号包裹JSON并转义内部双引号
使用双引号包裹整个JSON内容,内部的双引号用反引号()转义,这样PowerShell会解析$pass`变量,同时保证JSON格式正确:
# build email message body and send it $headers=@{} $headers.Add("accept", "application/json") $headers.Add("Content-Type", "application/json") $headers.Add("X-Smtp2go-Api-Key", "api-3A583xxxxxxxxxxx") $response = Invoke-WebRequest -Uri 'https://api.smtp2go.com/v3/email/send' -Method POST -Headers $headers -ContentType 'application/json' -Body "{`"sender`":`"merakiapi@mydomain.co.uk`",`"to`":[`"me@mydomain.co.uk`"],`"subject`":`"Password for Guest WiFi`",`"html_body`":`"The new password is $pass`"}"
方案2:使用Here-String(易读性更高)
Here-String允许你直接编写包含双引号的字符串,无需频繁转义,同时支持变量解析:
# build email message body and send it $headers=@{} $headers.Add("accept", "application/json") $headers.Add("Content-Type", "application/json") $headers.Add("X-Smtp2go-Api-Key", "api-3A583xxxxxxxxxxx") # Here-String定义JSON内容 $bodyContent = @" {"sender":"merakiapi@mydomain.co.uk","to":["me@mydomain.co.uk"],"subject":"Password for Guest WiFi","html_body":"The new password is $pass"} "@ $response = Invoke-WebRequest -Uri 'https://api.smtp2go.com/v3/email/send' -Method POST -Headers $headers -ContentType 'application/json' -Body $bodyContent
方案3:哈希表转JSON(最推荐,避免手动格式错误)
通过构建哈希表,再用ConvertTo-Json自动生成符合规范的JSON字符串,彻底避免手动拼接引号的问题:
# build email message body and send it $headers=@{} $headers.Add("accept", "application/json") $headers.Add("Content-Type", "application/json") $headers.Add("X-Smtp2go-Api-Key", "api-3A583xxxxxxxxxxx") # 定义邮件参数哈希表 $emailParams = @{ sender = "merakiapi@mydomain.co.uk" to = @("me@mydomain.co.uk") subject = "Password for Guest WiFi" html_body = "The new password is $pass" } # 转换为标准JSON字符串 $bodyJson = $emailParams | ConvertTo-Json $response = Invoke-WebRequest -Uri 'https://api.smtp2go.com/v3/email/send' -Method POST -Headers $headers -ContentType 'application/json' -Body $bodyJson
额外优化建议
读取密码文件时,添加-Raw和Trim()参数,避免文件中的换行符或空格被带入密码:
$pass = (Get-Content $PSScriptRoot\password.txt -Raw).Trim()
内容的提问来源于stack exchange,提问作者Beckyboo
相关产品推荐
相关产品推荐

