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

如何在Lettre Builder中为内嵌邮件图片附件命名?

解决Lettre内嵌图片在Gmail显示“noname”的问题

问题核心是你未给内嵌图片附件显式指定文件名,导致Gmail无法识别附件名称,默认显示“noname”。以下是具体解决方法:

关键操作:给内嵌附件设置文件名

使用Lettre的Attachment::new_inline()方法时,传入你想要的文件名(比如"logo.png"),这个文件名会被写入邮件头的Content-Disposition和Content-Type字段,Gmail会读取该字段显示附件名称。

完整代码示例

use lettre::{
    message::{Attachment, MultiPart, SinglePart},
    Message, SmtpTransport, Transport,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 读取本地图片文件
    let image_data = std::fs::read("assets/logo.png")?;

    // 构建内嵌图片,指定文件名和对应MIME类型
    let inline_img = Attachment::new_inline("logo.png")
        .body(image_data, "image/png".parse()?);

    // HTML内容通过cid引用内嵌图片(cid值需和文件名完全一致)
    let html_content = SinglePart::html(r#"
        <h3>内嵌图片示例</h3>
        <img src="cid:logo.png" alt="站点Logo" />
    "#);

    // 组装多部分邮件
    let email = Message::builder()
        .from("your_email@example.com".parse()?)
        .to("recipient@example.com".parse()?)
        .subject("带内嵌图片的测试邮件")
        .multipart(MultiPart::mixed().singlepart(html_content).attachment(inline_img))?;

    // 发送邮件(替换为你的SMTP配置)
    let mailer = SmtpTransport::relay("smtp.example.com")?.build();
    mailer.send(&email)?;

    Ok(())
}

额外注意事项

  • HTML中的cid:xxx必须和new_inline()传入的文件名完全匹配,否则图片无法正常内嵌显示
  • 确保MIME类型(如image/png)和图片实际格式一致,避免邮件客户端识别错误
  • 若仍有问题,可手动添加Content-Disposition头显式指定文件名:
use lettre::header::{ContentDisposition, DispositionParam, DispositionType};

let inline_img = Attachment::new_inline("logo.png")
    .header(ContentDisposition {
        disposition: DispositionType::Inline,
        parameters: vec![DispositionParam::Filename("logo.png".into())],
    })
    .body(image_data, "image/png".parse()?);

内容的提问来源于stack exchange,提问作者Joao Paulo Bianchi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:37:20