在电子邮件正文中显示 Python HTML 表

2024-01-23

我编写了一个 python 脚本来查询数据库并以 HTML 表格式显示数据。我怎样才能让这个代码以表格的形式显示在电子邮件中?

我尝试将代码粘贴到第二个脚本(EMAIL)的 html 标签内,但它不读取 python 代码,仅读取 HTML。

            import pyodbc
            import cgi

            def htmlTop():
                print("""Content-type:text/html\n\n
                      <!DOCTYPE html>
                      <html lang='en'>
                      <head>
                        <meta charset="utf-8"/>
                        <title>My Tabmle</title>
                        </head>
                        <body>""")
            def selectCOAStatus(cnxn, cursor):
                cursor.execute('''SELECT * from mytable''')
                data = cursor.fetchall()
                return data

            def htmlTail():
                print("""</body>
                    </html>""")

            def connectDB():
                conn_str = (
                    r'DRIVER={SQL Server};'
                    r'SERVER=test;'
                    r'DATABASE=test;'
                    r'Trusted_Connection=yes;'
                )
                cnxn = pyodbc.connect(conn_str)
                cursor = cnxn.cursor()
                return cnxn, cursor



            def displayData(data):
                print("<table border='1'")
                print("<tr>")
                print("<th>Date</th>")
                print("<th>Count</th>")
                print("<th>Status</th>")
                print("</tr>")

                for row in data:
                    print("<tr>")
                    print("<td>{0}</td>".format(row[0]))
                    print("<td>{0}</td>".format(row[1]))
                    print("<td>{0}</td>".format(row[2]))
                    print("</tr>")
                print("</table>")

            if __name__ == "__main__":
                try:
                    htmlTop()
                    cnxn, cursor = connectDB()
                    data = selectCOAStatus(cnxn, cursor)
                    cursor.close()
                    displayData(data)
                    htmlTail()
                except:
                    cgi.print_exception()

电子邮件代码

导入smtplib

            from email.mime.multipart import MIMEMultipart
            from email.mime.text import MIMEText

            # me == my email address
            # you == recipient's email address
            me = "[email protected] /cdn-cgi/l/email-protection"
            you = "[email protected] /cdn-cgi/l/email-protection"

            # Create message container - the correct MIME type is 
            multipart/alternative.
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Link"
            msg['From'] = me
            msg['To'] = you

            # Create the body of the message (a plain-text and an HTML 
            version).
            text = "Hi!\nHow are you?\nHere is the link you 
            wanted:\nhttp://www.python.org"
            html = htmlTop()

            # Record the MIME types of both parts - text/plain and 
            text/html.
            part1 = MIMEText(text, 'plain')
            part2 = MIMEText(html, 'html')

            # Attach parts into message container.
            # According to RFC 2046, the last part of a multipart message, 
             in this case
            # the HTML message, is best and preferred.
            msg.attach(part1)
            msg.attach(part2)

            # Send the message via local SMTP server.
            s = smtplib.SMTP('email.fpl.com')
            # sendmail function takes 3 arguments: sender's address, 
             recipient's address
            # and message to send - here it is sent as one string.
            s.sendmail(me, you, msg.as_string())
            s.quit()                

我希望此 HTML 表格显示在我的电子邮件正文中。


我能够将数据存入表中。我修复了 for 循环以迭代所有行并返回值。它只返回一行,而我的查询返回多行。为什么会发生这种情况?

导入pyodbc 导入cgi 导入html

            conn_str = (
                    r'DRIVER=test'
                    r'SERVER=test;'
                    r'DATABASE=test;'
                    r'Trusted_Connection=yes;'
                )
            cnxn = pyodbc.connect(conn_str)
            cursor = cnxn.cursor()


            cursor.execute('''SELECT * from my table '''
            for row in cursor:
                    html_code = """
                    <!doctype html>
                <html>
                <head>
                <meta charset="utf-8">
                <title>Untitled Document</title>
                <body>
                    <table border='1'
                    <tr>
                        <th>Date</th>
                        <th>Count</th>
                        <th>Status</th>
                    </tr>
                    <tr>
                        <td>{}</td>
                        <td>{}</td>
                        <td>{}</td>
                    </tr>
                    </table>
                    </body>
                    </html>""".format(row[0],row[1],row[2])
            print(html_code)


            import smtplib

            from email.mime.multipart import MIMEMultipart
            from email.mime.text import MIMEText

            # me == my email address
            # you == recipient's email address
            me = "[email protected] /cdn-cgi/l/email-protection"
            you = "[email protected] /cdn-cgi/l/email-protection"

            # Create message container - the correct MIME type is 
            multipart/alternative.
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Link"
            msg['From'] = me
            msg['To'] = you

            # Create the body of the message (a plain-text and an HTML version).
            text = "Hi!\nHow are you?\nHere is the link you 
            wanted:\nhttp://www.python.org"
            html = html_code

            # Record the MIME types of both parts - text/plain and text/html.
            part1 = MIMEText(text, 'plain')
            part2 = MIMEText(html, 'html')

            # Attach parts into message container.
            # According to RFC 2046, the last part of a multipart message, in this 
            case
            # the HTML message, is best and preferred.
            msg.attach(part1)
            msg.attach(part2)

            # Send the message via local SMTP server.
            s = smtplib.SMTP('email.fpl.com')
            # sendmail function takes 3 arguments: sender's address, recipient's 
            address
            # and message to send - here it is sent as one string.
            s.sendmail(me, you, msg.as_string())
            s.quit()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在电子邮件正文中显示 Python HTML 表 的相关文章

随机推荐

  • 带有 Google 服务帐户主题的generate_access_token()

    在 python 中 我尝试通过服务帐户调用 GMail API委派全域权限 https developers google com identity protocols oauth2 service account authorizing
  • 检索具有 CLSID 的组件的 COM 类工厂错误:8000401a

    从上次开始 我多次收到以下错误 因为我正在使用 Microsoft Word dll 创建 Word 文件 并将其进一步附加到邮件中 Server Error in Application Retrieving the COM class
  • 我如何快速更新其他控制器的用户界面?

    我的应用程序中有几个控制器 当我的应用程序调用一个控制器中的一个函数时 我想更新其他控制器的 UI 我怎样才能做到这一点 class FirstViewController UIViewController func updateUI cl
  • 通过 svnsync 复制 SVN 存储库时如何解决此错误?

    我正在使用 svnsync 复制存储库 并且每次在同一修订版上都会收到此错误 正在传输文件数据 svnsync REPORT of https svn1 avlux net xxxxxx net https svn1 avlux net x
  • Java wait()、notify() 的实现与锁有显着不同吗?

    出于好奇 当Java实现wait 和notify 方法时 它们真的只是使用锁吗 即 wait 获取互斥体 notify 释放互斥体 notifyAll 释放所有互斥体 当然在同一个对象中 使用wait 和notify 除了比使用锁方便之外还
  • 如何向 iOS 14 小部件添加按钮

    我正在尝试向具有系列类型 systemLarge 的小部件添加按钮 我想在不打开应用程序的情况下执行一些代码 有人知道该怎么做吗 例如 快捷方式应用程序小部件包含您可以点击以执行快捷方式而无需打开应用程序的按钮 小部件是只读的 快捷方式应用
  • 使用 ElasticSearch 术语聚合动态创建的存储桶构建 Kibana 直方图

    我希望能够结合Kibana 术语图 能够根据特定属性值的唯一性创建存储桶 以及直方图 根据查询将数据分成桶 然后根据时间说明日期 总的来说 我想创建一个直方图 但我只想根据一个查询的结果创建直方图 而不是像在Kibana 演示应用程序 ht
  • IE10有flex-grow吗?

    Caniuse 使用 ms 前缀表示部分支持http caniuse com search flex grow http caniuse com search flex grow据我所知 然而 当测试 ms flex grow 在 IE10
  • 使用 OpenCV 检测越线人员

    我想统计从两边越线的人数 我有一个放置在天花板上的摄像机 拍摄线条所在的地板 因此摄像机只能看到人的头顶 因此它更多的是物体检测而不是人检测 是否有针对此问题或类似问题的示例解决方案 那我可以向他们学习吗 编辑1 任何时刻都有不止一个人越线
  • python:从字符串模板中提取变量

    我熟悉使用将变量插入字符串的能力模板 https docs python org 2 library string html template strings 像这样 Template value is between min and ma
  • 如何判断该点是否在四面体中?

    我知道四面体的所有坐标和我想确定的点 那么有人知道该怎么做吗 我试图确定该点属于四面体的每个三角形 如果它对所有三角形都成立 则该点位于四面体中 但这绝对是错误的 对于四面体的每个平面 检查该点是否与其余顶点位于同一侧 bool SameS
  • dplyr 中字符串的新列[重复]

    这个问题在这里已经有答案了 我有一个数据框 library tidyverse df lt tribble col1 col2 1 2 现在我想创建一个专栏 我有一个字符串中的新列的名称 它确实像这样工作 df gt mutate col3
  • 可以在运行时将目录添加到类路径中吗?

    为了更好地理解 Java 中的工作原理 我想知道是否可以在运行时动态地将目录添加到类路径中 例如 如果我启动一个 jar using java jar mycp jar 并输出java class path财产 我可能会得到 java cl
  • 类型错误:+ 不支持的操作数类型:“生成器”和“生成器”

    我在目标函数中添加三个表达式时遇到问题 我用了quicksum构建每个表达式 但是 当我尝试将它们添加在一起时 出现错误 无法在 生成器 类上使用 操作数 这是我的代码的最后一部分 the shipping cost expression
  • Angular是否需要取消订阅this.activatedRoute订阅

    My code ngOnInit this activatedRoute params subscribe params Params gt do stuff this activatedRoute data subscribe data
  • Builders 页面从 Eclipse 项目属性中消失

    我不知道我的带有最新 Android SDK 和最新 Sequoyah 插件的 Eclipse Helios 发生了什么 突然 我在项目属性中看不到 构建器 页面 不是工作区中的单个项目 我怎样才能恢复这个页面 检查您目前处于哪个视角 右上
  • 如何处理ETIMEDOUT错误?

    如何处理此调用的 etimedout 错误 var remotePath myremoteurltocopy var localStream fs createWriteStream myfil var out request uri re
  • 在Linux中设置Mysql++

    我想在linux中用C 连接mysql数据库 在我的本地计算机上 我运行 Ubuntu 并安装了 mysql 服务器和客户端软件包 sudo apt get install mysql server mysql client 我碰到Mysq
  • 有什么方法可以获得断点特定的宽度类吗?

    Bootstrap 4 包括宽度类别 https getbootstrap com docs 4 0 utilities sizing w 25 w 50 w 75 w 100 我只想为某些断点及以上指定宽度 例如 w md 25 等 是否
  • 在电子邮件正文中显示 Python HTML 表

    我编写了一个 python 脚本来查询数据库并以 HTML 表格式显示数据 我怎样才能让这个代码以表格的形式显示在电子邮件中 我尝试将代码粘贴到第二个脚本 EMAIL 的 html 标签内 但它不读取 python 代码 仅读取 HTML