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

时间:2019-08-09 16:38:45

标签: python

我编写了一个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 = "test@aol.com"
            you = "test@aol.com"

            # 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表显示在我的电子邮件正文中。

2 个答案:

答案 0 :(得分:1)

尝试

{
    "version": "2.0.0",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": true,
        "panel": "new"
    },
    "tasks": [
        {
            "label": "cmake",
            "type": "shell",
            "command": "cmake -DCMAKE_BUILD_TYPE=Debug ..",
            "options": {
                "cwd": "${workspaceRoot}/build"
            }
        },
        {
            "label": "make",
            "type": "shell",
            "options": {
                "cwd": "${workspaceRoot}/build"
            },
            "command": "make -j8",
            "dependsOn": [
                "cmake"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

也是一种用于HTML电子邮件的更简单方法

print("<td>%s</td>" % row[0] )

答案 1 :(得分:0)

我能够将数据放入表中。我修复了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 = "test@aol.com"
            you = "test@aol.com"

            # 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()