Rust lettre 0.10.0-rc-4将图片Vec转为SinglePart添加邮件报错咨询
问题核心原因
singlepart() 方法的入参要求是单个 SinglePart 结构体,而你编写的 add_attachment 函数返回的是存储了多个 SinglePart 的 Vec 集合,类型不匹配所以触发编译报错。
可行解决方案
你需要使用MultiPart容器来承载邮件的正文+所有图片附件,具体修改逻辑如下:
- 先构建邮件的基础正文部分,再创建
related类型的MultiPart容器用来组合正文和内联图片:
// 示例:构建HTML格式的邮件正文 let html_part = SinglePart::builder() .header(header::ContentType::TEXT_HTML) .body("<p>此处替换为你的实际邮件正文内容</p>".to_string()); // 初始化混合内容容器 let mut mail_multipart = MultiPart::related().singlepart(html_part);
- 遍历
add_attachment返回的所有图片附件,逐个添加到MultiPart容器中:
for img_part in add_attachment(email_order.body.products.clone()) { mail_multipart = mail_multipart.singlepart(img_part); }
- 邮件构建时调用
multipart方法传入组装完成的混合内容即可:
let email = Message::builder() .from("发件人邮箱".parse().unwrap()) .to("收件人邮箱".parse().unwrap()) .subject("邮件主题") .multipart(mail_multipart) .unwrap();
附加代码优化提示
你当前编写的add_attachment函数存在逻辑问题:遍历过程中一直取image_body[0]的属性,最终只会重复添加第一张产品图片,可修改为以下逻辑:
fn add_attachment(image_body: Vec<calc_price::products::Products>) -> Vec<lettre::message::SinglePart> { image_body.iter().enumerate().map( |(i, product)| { let content_id = format!("{i}-0-{}", product.picture.name); let file_path = format!("src/images/{}.jpeg", product.picture.name); let filebody = fs::read(file_path).unwrap(); let content_type = "image/jpeg".parse().unwrap(); Attachment::new_inline(content_id).body(filebody, content_type) }) .collect() }
内容的提问来源于stack exchange,提问作者Klod Lala
相关产品推荐
相关产品推荐

