python如何发送html,且html内存在链接外部css样式

需求:需要将我的自动化测试报告以邮件的形式发送给团队
遇到的问题:我测试了一把,报告发送成功了,但是打开没有数据
猜测:html内存在link标签引用了外部css样式导致的,而这些个css没有发送过去

提问:如何正确的将html发送给团队,且打开无异常,数据正确
代码如下:

img

发送邮件成功后打开如下图:

img

本地打开如下图:

img

你确定你发送的邮箱支持外部CSS链接吗,如果不太行的话,你可以把css提取出来,放到内联样式了

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests
from bs4 import BeautifulSoup


def extract_css(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    styles = soup.find_all('style')
    css = ''
    for style in styles:
        css += style.get_text()
    return css


def embed_css(html, css):
    soup = BeautifulSoup(html, 'html.parser')
    style_tag = soup.new_tag('style')
    style_tag.string = css
    head_tag = soup.head
    if head_tag:
        head_tag.append(style_tag)
    else:
        head_tag = soup.new_tag('head')
        head_tag.append(style_tag)
        soup.insert(0, head_tag)
    return str(soup)


def send_email(sender, recipient, subject, html_content):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recipient

    # Extract CSS styles from the HTML content
    css = extract_css('http://example.com/styles.css')

    # Embed CSS styles into the HTML content
    html_content = embed_css(html_content, css)

    # Attach HTML content to the email
    html_part = MIMEText(html_content, 'html')
    msg.attach(html_part)

    # Send the email
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('username', 'password')
        server.sendmail(sender, recipient, msg.as_string())


# Example usage
sender_email = 'sender@example.com'
recipient_email = 'recipient@example.com'
email_subject = 'HTML email with embedded CSS'

html_content = '''
<html>
<head>
    <title>HTML Email</title>
    <link rel="stylesheet" type="text/css" href="http://example.com/styles.css">
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is an HTML email with embedded CSS styles.</p>
</body>
</html>
'''

send_email(sender_email, recipient_email, email_subject, html_content)