Search code examples
delphiindy

Indy 9 - Email with body as RTF and with attachments


I'm trying to send a email with indy 9:

  • Body as RTF, formatted from a TRichEdit
  • A single file attached

The code:

 Message := TIdMessage.Create()
 Message.Recipients.EMailAddresses := '[email protected]';

 Message.ContentType := 'multipart/alternative';

 with TIdText.Create(Message.MessageParts) do
   ContentType := 'text/plain';

 with TIdText.Create(Message.MessageParts) do
 begin
   ContentType := 'text/richtext';
   Body.LoadFromFile('c:\bodymsg.rtf');
 end;

 TIdAttachment.Create(Message.MessageParts, 'c:\myattachment.zip');

 // send...

The result: body comes empty (using web gmail and outlook 2010 as clients).

I'm already tried other content types without success:

  • text/rtf
  • text/enriched

NOTE: I'll not upgrade to Indy 10.


Solution

  • You are setting the TIdMessage.ContentType to the wrong value when the TIdAttachment is present. It needs to be set to 'multipart/mixed' instead because you are mixing the 'multipart/alternative' and 'application/x-zip-compressed' parts together at the same top-level MIME nesting level, whereas the 'text/...' parts are children of the 'multipart/alternative' part instead.

    Have a look at the following blog article I wrote on the Indy website:

    HTML Messages

    The email structure you are trying to create is covered by the "Plain-text and HTML and attachments: Non-related attachments only" section. You would just replace HTML with RTF, and ignore the TIdText object for the 'multipart/alternative' part because TIdMessage in Indy 9 will create that internally for you (it is explicitly needed in Indy 10 because of its deeper MIME support than Indy 9 has).

    Try this:

    Message := TIdMessage.Create()
    Message.Recipients.EMailAddresses := '[email protected]';
    
    Message.ContentType := 'multipart/mixed';
    
    with TIdText.Create(Message.MessageParts) do
    begin
      ContentType := 'text/plain';
      Body.Text := 'You need an RTF reader to view this message';
    end;
    
    with TIdText.Create(Message.MessageParts) do
    begin
      ContentType := 'text/richtext';
      Body.LoadFromFile('c:\bodymsg.rtf');
    end;
    
    TIdAttachment.Create(Message.MessageParts, 'c:\myattachment.zip');
    
    // send...