You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用PowerShell发送带列表数据的HTML表格邮件失败问题

Python调用PowerShell发送HTML表格邮件无数据问题解决

问题现象

通过Python调用PowerShell发送包含列表数据的HTML表格邮件,仅显示表格标题,数据单元格为空。

核心问题

  1. Python到PowerShell的数据传递错误:原代码中Python的res列表未正确传递给PowerShell脚本,PowerShell里的$res变量未被赋值,导致$resArray为空。
  2. PowerShell字符串处理冗余:使用Out-String处理表格行,可能引入多余格式,导致HTML渲染异常。

修复方案

步骤1:正确传递Python数据到PowerShell

将Python的res列表转为逗号分隔的字符串,作为参数传递给PowerShell脚本,而非直接传入列表对象。

步骤2:修改PowerShell脚本接收参数

在PowerShell脚本中通过$args接收传递的参数,再拆分处理。

步骤3:优化表格行生成逻辑

移除Out-String,直接通过-join拼接表格行字符串,避免多余格式干扰。

修复后的完整代码

Python代码

res = ['1234', '235']
# 将列表转为逗号分隔的字符串
res_str = ','.join(res)

powershell_script = r'''
# 接收Python传递的参数并拆分数组
$resArray = $args[0] -split ','

# 生成表格行,直接拼接字符串
$tableBody = $resArray | ForEach-Object {
    "<tr><td>$($_)</td></tr>"
} -join ''

$body = @"
<html>
<head>
<style>
table {
    border-collapse: collapse;
    width: 50%;
}

table, th, td {
    border: 1px solid black;
    padding: 8px;
    text-align: center;
}
</style>
</head>
<body>
<h2>Table of 'res' Values</h2>
<table>
  <tr>
    <th>Value</th>
  </tr>
  $tableBody
</table>
</body>
</html>
"@

# 邮件参数配置(替换为实际值)
$toEmail = "收件人邮箱"
$fromEmail = "发件人邮箱"
$subject = "测试HTML表格邮件"
$smtpServer = "SMTP服务器地址"
$smtpPort = 587 # 根据实际情况修改

$emailParams = @{ 
   To = $toEmail 
   From = $fromEmail 
   Subject = $subject 
   Body = $body 
   BodyAsHtml = $true 
   SmtpServer = $smtpServer 
   Port = $smtpPort 
} 

# 发送邮件
try { 
   Send-MailMessage @emailParams
   Write-Host "Email sent successfully!" 
} 
catch { 
   Write-Host "An error occurred while sending the email: $($_.Exception.Message)" 
}
'''

# 调用PowerShell,传递res_str作为参数
import subprocess
subprocess.run(["powershell", "-ExecutionPolicy", "Bypass", "-Command", powershell_script, res_str], check=True, text=True)

关键说明

  • subprocess.run中,将res_str作为参数放在PowerShell脚本之后,确保PowerShell能通过$args[0]获取到数据。
  • 使用-join ''替代Out-String,保证表格行直接拼接成连续的HTML字符串,避免换行或空白导致的渲染问题。
  • 确保BodyAsHtml = $true,否则邮件会将HTML代码作为纯文本显示。

内容的提问来源于stack exchange,提问作者SQLLER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:00:08