You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML表格转为图片并通过邮件发送?

解决方法:HTML表格转图片并发送邮件

一、将HTML表格转换为图片

可以使用imgkit库实现HTML到图片的转换,它依赖wkhtmltopdf工具,步骤如下:

1. 安装依赖

  • 安装Python库:
pip install imgkit pandas tabulate gspread
  • 安装wkhtmltopdf:
    • Windows:下载官方安装包完成安装后,将其路径添加到系统环境变量
    • macOS:执行brew install wkhtmltopdf
    • Linux:执行sudo apt-get install wkhtmltopdf

2. 添加转图片逻辑

在现有代码基础上,封装HTML转图片的函数:

import imgkit

def html_to_image(html_content, output_path="table_image.png"):
    # 配置wkhtmltopdf路径(若未添加到环境变量则需指定)
    config = imgkit.config(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe") # Windows示例路径
    # 转换HTML为图片
    imgkit.from_string(html_content, output_path, config=config)
    return output_path

# 使用示例
plant_id = 12404
html_table = gsheet_get_location(plant_id)
image_path = html_to_image(html_table)

二、发送包含图片的邮件

使用Python内置的smtplib和email库实现邮件发送,支持图片作为附件或嵌入正文:

1. 发送图片作为附件

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

def send_email_with_attachment(image_path, sender_email, sender_password, receiver_email, subject):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加邮件正文
    body = "以下是从Google Sheets获取的传感器位置表格图片"
    msg.attach(MIMEText(body, 'plain'))

    # 添加图片附件
    with open(image_path, 'rb') as f:
        img = MIMEImage(f.read())
        img.add_header('Content-Disposition', 'attachment', filename='sensor_location.png')
        msg.attach(img)

    # 连接SMTP服务器并发送邮件(以Gmail为例,其他邮箱需修改SMTP地址和端口)
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, sender_password)
        server.send_message(msg)

# 使用示例
send_email_with_attachment(
    image_path=image_path,
    sender_email="your_email@gmail.com",
    sender_password="your_app_password", # Gmail需使用应用专用密码
    receiver_email="recipient@example.com",
    subject="传感器位置表格图片"
)

2. 将图片嵌入邮件正文

若要让图片直接显示在邮件正文中,可使用以下代码:

def send_email_with_inline_image(image_path, sender_email, sender_password, receiver_email, subject):
    msg = MIMEMultipart('related')
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 创建包含HTML正文的替代部分
    msg_alternative = MIMEMultipart('alternative')
    msg.attach(msg_alternative)

    # 嵌入图片的HTML代码
    html_body = f"""
    <p>以下是传感器位置表格:</p>
    <img src="cid:table_image" alt="传感器位置表格">
    """
    msg_alternative.attach(MIMEText(html_body, 'html'))

    # 添加图片并设置CID用于正文引用
    with open(image_path, 'rb') as f:
        img = MIMEImage(f.read())
        img.add_header('Content-ID', '<table_image>')
        msg.attach(img)

    # 发送邮件
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, sender_password)
        server.send_message(msg)

三、整合完整流程

将所有步骤整合为可直接执行的代码:

import gspread
import pandas as pd
from tabulate import tabulate
import imgkit
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

def gsheet_get_location(plant_id):
    # 读取Google Sheets数据
    sa = gspread.service_account(filename="Service_acount.json")
    sh = sa.open("Parameters Check")
    wks = sh.worksheet("location_sensors")
    wks_df = pd.DataFrame(wks.get_all_records())
    plant_filtered = wks_df.query(f"Plant_id == {plant_id}")
    return tabulate(plant_filtered, headers='keys', tablefmt='html')

def html_to_image(html_content, output_path="table_image.png"):
    # 配置wkhtmltopdf路径(根据系统修改)
    config = imgkit.config(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe")
    imgkit.from_string(html_content, output_path, config=config)
    return output_path

def send_email_with_attachment(image_path, sender_email, sender_password, receiver_email, subject):
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText("以下是从Google Sheets获取的传感器位置表格图片", 'plain'))
    
    with open(image_path, 'rb') as f:
        img = MIMEImage(f.read())
        img.add_header('Content-Disposition', 'attachment', filename='sensor_location.png')
        msg.attach(img)
    
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, sender_password)
        server.send_message(msg)

# 执行流程
if __name__ == "__main__":
    target_plant_id = 12404
    html_table = gsheet_get_location(target_plant_id)
    image_path = html_to_image(html_table)
    send_email_with_attachment(
        image_path=image_path,
        sender_email="your_email@gmail.com",
        sender_password="your_app_password",
        receiver_email="recipient@example.com",
        subject="传感器位置表格图片"
    )

注意事项

  • 不同邮箱的SMTP配置不同:QQ邮箱SMTP地址为smtp.qq.com(端口465),网易邮箱为smtp.163.com(端口465)
  • Gmail需开启两步验证并创建应用专用密码才能通过SMTP发送邮件
  • 确保wkhtmltopdf路径配置正确,否则会导致转换失败

内容的提问来源于stack exchange,提问作者Andriell Henrique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:45:38