张怼怼呀 2023-05-26 14:04 采纳率: 71.4%
浏览 35

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

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

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

img

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

img

本地打开如下图:

img

  • 写回答

1条回答 默认 最新

  • 杰 c 2023-05-26 14:37
    关注

    你确定你发送的邮箱支持外部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)
    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月26日

悬赏问题

  • ¥15 u盘问题:盘符不显示 无媒体
  • ¥50 R语言读取nc按月均值转为tif
  • ¥30 智能车串级pid调参
  • ¥15 visual studio code翻译老是错误
  • ¥20 卫星测高数据的高程转换
  • ¥15 爬取招聘网站数据信息
  • ¥15 安装完tensorflow,import tensorflow as tf后报错,如何解决?
  • ¥15 ultralytics库导出onnx模型,模型失去预测能力
  • ¥15 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题