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

Python smtplib生成HTML邮件:嵌入签名图片及超链接问题求助

解决方案:嵌入带超链接的签名图片到HTML邮件

要实现签名里的图片嵌入(而非附件)并排版,核心是用**MIMEMultipart('related')关联HTML内容和图片资源,通过Content-ID (cid)**在HTML中引用嵌入的图片,同时用内联CSS做兼容邮件客户端的排版。下面是完整的实现步骤和代码:

核心思路

  1. 放弃单独的MIMEText,改用MIMEMultipart('related')作为邮件容器,它能关联HTML文本和嵌入的媒体资源(图片)。
  2. 把本地图片转为MIMEImage对象,设置Content-ID和Content-Disposition: inline,确保图片嵌入邮件而非成为附件。
  3. 在HTML中用cid:xxx引用对应图片,并用<a>标签包裹图片添加超链接。
  4. 用table布局+内联CSS做签名排版,因为多数邮件客户端(如Outlook)对现代CSS支持有限,table兼容性最好。

完整代码示例

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

def add_inline_image(email_msg, image_path, cid_name):
    """将本地图片转为嵌入邮件的MIMEImage对象"""
    with open(image_path, 'rb') as img_file:
        img_data = img_file.read()
    
    # 创建MIMEImage对象
    img_part = MIMEImage(img_data)
    # 设置Content-ID,HTML中用cid:cid_name引用
    img_part.add_header('Content-ID', f'<{cid_name}>')
    # 标记为inline,避免被当作附件
    img_part.add_header('Content-Disposition', 'inline', filename=os.path.basename(image_path))
    email_msg.attach(img_part)

# 1. 创建关联型多部分邮件容器
msg = MIMEMultipart('related')
msg['Subject'] = "测试带签名图片的邮件"
msg['From'] = "your_email@example.com"
msg['To'] = "recipient@example.com"

# 2. 编写HTML内容,包含签名排版(用table保证兼容性)
html_content = """
<html>
<head></head>
<body>
  <p>这里是邮件正文内容...</p>

  <!-- 签名区域:顶部加分隔线,左侧大图+底部小图 -->
  <table style="margin-top:20px; border-top:1px solid #eeeeee; padding-top:15px;">
    <tr>
      <!-- 左侧大图,带超链接 -->
      <td>
        <a href="https://your-big-image-link.com" target="_blank" style="text-decoration:none;">
          <img src="cid:big_signature" alt="公司Logo" style="width:200px; height:auto; border:none;">
        </a>
      </td>
    </tr>
    <tr>
      <!-- 底部小图,带超链接 -->
      <td style="padding-top:10px;">
        <a href="https://your-small-image-link.com" target="_blank" style="text-decoration:none;">
          <img src="cid:small_signature" alt="认证标识" style="width:100px; height:auto; border:none;">
        </a>
      </td>
    </tr>
  </table>
</body>
</html>
"""

# 3. 添加HTML文本部分到邮件
html_part = MIMEText(html_content, 'html', 'utf-8')
msg.attach(html_part)

# 4. 嵌入签名图片
add_inline_image(msg, r"C:\Users\Me\Desktop\image1.png", "big_signature")
add_inline_image(msg, r"C:\Users\Me\Desktop\image2.png", "small_signature")

# 5. 发送邮件(替换为你的SMTP配置)
with smtplib.SMTP('smtp.example.com', 587) as server:
    server.starttls()
    server.login('your_email_username', 'your_email_password')
    server.send_message(msg)

关键细节说明

  • 为什么不用本地路径?:邮件客户端不会读取发送者的本地文件,必须将图片二进制数据嵌入邮件,通过cid引用才能显示。
  • Content-Disposition: inline:这是避免图片变成附件的关键,加上这个头,邮件客户端会将图片嵌入到HTML内容中。
  • 邮件排版注意事项:尽量用内联CSS(style属性),不要用外部样式表或
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:47:02