【问题标题】:Display Python HTML Table in Body of Email在电子邮件正文中显示 Python HTML 表格
【发布时间】:2019-08-10 04:47:35
【问题描述】:

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

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    试试

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

    也是一种更简单的 html 电子邮件方法

    from mailer import Mailer
    from mailer import Message
    
    message = Message(From="me@example.com",
                  To="you@example.com")
    message.Subject = "An HTML Email"
    message.Html = """<p>Hi!<br>
                   How are you?<br></p>"""
    
    sender = Mailer('smtp.example.com')
    sender.send(message)
    

    【讨论】:

    • 谢谢。邮件程序代码更高效且更易于使用。但是,我的代码有效,但循环仅将我带回表中的“ONE”行。如果我单独运行查询,我有不止一行。
    【解决方案2】:

    我能够将数据放入表中。我修复了我的 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 2020-01-14
      • 1970-01-01
      • 2011-04-10
      • 2012-05-21
      • 2013-12-16
      • 1970-01-01
      相关资源
      最近更新 更多