How to create multipart/related attachment of JPG file in Delphi?

99 Views Asked by At

I'm trying to create multipart/related attachment with such code:

var
 Msg: TIdMessage;
 Attachment: TIdAttachmentFile;
begin
 Msg := TIdMessage.Create(nil);
 try
  Attachment := TIdAttachmentFile.Create(Msg.MessageParts, 'D:\temp\CachedImage.jpg');
  Attachment.ContentType := 'multipart/related';
  Attachment.ContentTransfer := 'binary';
  Attachment.ContentDisposition := 'attachment; filename="CachedImage.jpg"';
  Msg.SaveToFile('d:\temp\MyFile.eml');
 finally
  Msg.Free;
 end;
end;

I'm expecting that it saves the attached file as EML file. But it does not.

Saved only part of the header and nothing more:

MIME-Version: 1.0
Date: Sat, 25 Mar 2023 09:38:31 +0300
--
Content-Type: multipart/related;
    boundary="0dZDwVffh1i=_ZLFRXeMyvVY4y2H5QDJoX"

How to fix such issue? I'm using Delphi 10.4.2 with installed Indy version.

1

There are 1 best solutions below

0
Remy Lebeau On BEST ANSWER

The code you have shown is not even remotely close to being correct. Why would you assign a JPG file to be the multipart/related part itself?

Please read HTML Messages and New HTML Message Builder class on Indy's website for the proper way to use multipart/related in TIdMessage. You are supposed to put the JPG file inside of a multipart/related part that also holds a text/html part which the JPG is related to (ie, which refers to the JPG).

For example:

var
  Msg: TIdMessage;
  HTML: TIdText;
  Attachment: TIdAttachmentFile;
begin
  Msg := TIdMessage.Create(nil);
  try
    Msg.ContentType := 'multipart/related; type="text/html"'; 
    HTML := TIdText.Create(Msg.MessageParts, nil);
    HTML.Body.Text := '<img src="cid:12345">';
    HTML.ContentType := 'text/html';
    Attachment := TIdAttachmentFile.Create(Msg.MessageParts, 'D:\temp\CachedImage.jpg');
    Attachment.ContentID := '12345'
    Attachment.ContentType := 'image/jpeg';
    Attachment.ContentTransfer := 'binary';
    Msg.SaveToFile('d:\temp\MyFile.eml');
  finally
    Msg.Free;
  end;
end;

Or

var
  Msg: TIdMessage;
begin
  Msg := TIdMessage.Create(nil);
  try
    Builder := TIdMessageBuilderHtml.Create;
    try
      Builder.Html.Text := '<img src="cid:12345">';
      Builder.HtmlFiles.Add('D:\temp\CachedImage.jpg', '12345');
      Builder.FillMessage(Msg);
    finally
      Builder.Free;
    end;
    Msg.SaveToFile('d:\temp\MyFile.eml');
  finally
    Msg.Free;
  end;
end;