使用 smtplib 在电子邮件正文中发送带有彩色单元格的 HTML 输出表

Send HTML output table with coloured cells in email body using smtplib

提问人:minty_fresh 提问时间:10/18/2023 更新时间:10/18/2023 访问量:40

问:

我正在尝试发送一封自动电子邮件,并在电子邮件正文中显示一个表格。该表有 2 列,第 1 列中单元格的背景颜色会根据第 2 列中单元格的值而变化。

这是我正在使用的html模板:

<!DOCTYPE html>
<html>
<head>
    <title>Colored Cells</title>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>Source</th>
            <th>Available Data</th>
        </tr>
    </thead>
    <tbody>
        {% for item in data %}
            <tr style="background-color: {{ 'rgba(0, 128, 0, 0.5)' if item.check == True else 'rgba(255, 165, 0, 0.5)' }}">
                <td>{{ item.column1 }}</td>
                <td>{{ item.value }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

如果我运行我的 python 代码并使用此模板创建 html 输出,我就会得到我想要的。但是,当我尝试将此表放在电子邮件正文中时,颜色没有显示(表的其余部分看起来很好)。

这是我正在使用的 python 代码

def python_mail(sender_email, rec_email, email_text):

     smtp_server = smtplib.SMTP('smtp.office365.com', 587)  # Outward facing interface
     smtp_server.ehlo()
     smtp_server.starttls()  # Helps in Secure Connection
     smtp_server.ehlo
     smtp_server.login(sender_email, 'password123')
     smtp_server.sendmail(sender_email, rec_email, email_text)
     smtp_server.close()

这是 python 代码的其余部分(其中 html_output_colour 是输出 html,当我将其输出为 html 并在浏览器中打开它时工作正常):

    email_str += "Start of email body"

    sender_email = "[email protected]"
    rec_email = "[email protected]"

    msg = MIMEMultipart()
    html_part = MIMEText(html_output_colour, 'html')
    msg.attach(html_part)

    msg["Subject"] = subject

    # Send Email
    python_mail(sender_email, rec_email, msg.as_string())

有谁知道我怎样才能让它工作?

python html smtplib

评论


答: 暂无答案