如何在Delphi中创建JPG文件的multipart/related附件?
问题分析与解决
你的代码核心错误是把multipart/related直接赋值给了单个TIdAttachmentFile。multipart/related是MIME复合容器类型,用于组织多个关联内容(比如HTML正文+内嵌图片),不是单个文件附件的媒体类型。单个图片附件需要使用对应具体类型(如image/jpeg),而multipart/related应设置在整个消息或复合内容容器上。
修正后的基础代码
var Msg: TIdMessage; Attachment: TIdAttachmentFile; begin Msg := TIdMessage.Create(nil); try // 将multipart/related设置为整个消息的容器类型 Msg.ContentType := 'multipart/related; boundary=' + TIdMIMEBoundary.CreateBoundary; // 创建图片附件并指定正确的MIME类型 Attachment := TIdAttachmentFile.Create(Msg.MessageParts, 'D:\temp\CachedImage.jpg'); Attachment.ContentType := 'image/jpeg'; // 对应JPG图片的标准MIME类型 Attachment.ContentTransfer := 'binary'; Attachment.ContentDisposition := 'attachment; filename="CachedImage.jpg"'; // 保存完整EML文件 Msg.SaveToFile('d:\temp\MyFile.eml'); finally Msg.Free; end; end;
关键修正说明
- 把
multipart/related从单个附件移到TIdMessage的ContentType属性,让它作为整个消息的内容容器。 - 图片附件使用
image/jpeg作为ContentType,你也可以让Indy自动检测文件类型:Attachment.ContentType := IndyGetMIMETypeFromFile('D:\temp\CachedImage.jpg'); - Indy会自动处理
multipart/related的边界分割和内容封装,无需手动拼接。
进阶场景:内嵌图片+HTML正文
如果你的需求是用multipart/related关联HTML正文和内嵌图片,可参考以下代码:
var Msg: TIdMessage; TextPart: TIdText; Attachment: TIdAttachmentFile; begin Msg := TIdMessage.Create(nil); try Msg.ContentType := 'multipart/related; boundary=' + TIdMIMEBoundary.CreateBoundary; // 添加HTML正文部分 TextPart := TIdText.Create(Msg.MessageParts, nil); TextPart.ContentType := 'text/html'; TextPart.Body.Text := '<html><body><img src="cid:image1"></body></html>'; // 添加内嵌图片,通过Content-ID和正文关联 Attachment := TIdAttachmentFile.Create(Msg.MessageParts, 'D:\temp\CachedImage.jpg'); Attachment.ContentType := 'image/jpeg'; Attachment.ContentID := '<image1>'; // 和正文的cid引用对应 Attachment.ContentDisposition := 'inline'; // 设置为内嵌显示而非附件下载 Msg.SaveToFile('d:\temp\MyFile.eml'); finally Msg.Free; end; end;
内容的提问来源于stack exchange,提问作者Dmitry Belkeivch
相关产品推荐
相关产品推荐

