python - 可以以 XML 格式发送电子邮件的 Python 脚本
问题描述
是否可以通过使用 XML 文档在电子邮件正文中创建可以通过电子邮件发送 XML 分层格式的 Python 脚本。
只是为您提供背景知识,我在 XML 文档中更新了一些细节,并希望在电子邮件中输入相同的 XML 格式。
目前,我使用 XSL 来设置 XML 文档的样式,并使用 Python“lxml”库将 XML 转换为 HTML,但我当前的脚本正在删除最终输出中的 XML 标记。
因此,我正在寻找一种在我的输出中保留这些 XML 标记的方法,我最好使用 XML 到 HTML 的相同方法,因为我需要在我的自动电子邮件中加载这个 HTML 结构。
Python 脚本
from lxml import etree
xsl = etree.parse("tx.xsl")
updated = etree.XSLT(xsl)
xml = etree.parse("tx.xml")
html = updated(xml)
html.write("XML-Transformed.html")
XSL 代码
?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="ROOT">
<tr>
<td><xsl:value-of select="Summary"/></td>
</tr>
<tr>
<td><xsl:value-of select="customer_Name"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XML
<ROOT>
<Summary>ZZZZ</Summary>
<customer_Name>YYYY</customer_Name>
</ROOT>
电流输出
ZZZZ
YYYY
预期的
<Summary>ZZZZ</Summary>
<customer_Name>YYYY</customer_Name>
解决方案
XSLT 转换的工作方式是,您需要明确地将输出中所需的所有内容添加到转换中。此外,如果您希望浏览器显示这些 XML 标记,则需要对它们进行转义。
试试这个 XSLT 文件,在浏览器中打开结果,让我知道它是否是您需要的:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="ROOT">
<tr>
<td><Summary><xsl:value-of select="Summary"/></Summary></td>
</tr>
<tr>
<td><customer_Name><xsl:value-of select="customer_Name"/></customer_Name></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
编辑:如果您想要带有自定义标签的 HTML,您需要将它们显式添加到 XSLT 转换中 - 这次不要转义:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="ROOT">
<tr>
<td><Summary><xsl:value-of select="Summary"/></Summary></td>
</tr>
<tr>
<td><customer_Name><xsl:value-of select="customer_Name"/></customer_Name></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- python - 我可以在 pyglet 中使用归一化坐标进行绘制吗?
- java - 对嵌套数组列表结构的迭代显示出意外的结果
- for-loop - 如何让此代码仅复制与我的对象匹配条件匹配的行?目前如果复制每一行
- c# - 如何在 C# 中制作一个列表框在按钮单击时不重复项目?
- android-gradle-plugin - 在以下模块中发现重复的类 org.hamcrest.BaseDescription,如何解决?
- python - 按需将张量发送到分布式 TensorFlow 中的其他工作节点
- c - 添加 3D 模型时纹理映射消失
- php - 如何更正此 php 代码,以便在不生成错误代码的情况下发送电子邮件
- types - 了解以下函数的类型
- c# - 同时获取集合的第一个和最后一个元素