Mega Code Archive

 
Categories / Delphi / Ide Indy
 

How can I send HTML messages with attachments (using Indy)

Title: How can I send HTML messages with attachments (using Indy) Question: With the Indy IdMessage component you can easily send an HTML formatted e-mails without attachments, or plain text e-mails with attachments, but how can you send HTML message WITH attachments... Answer: With the IdMessage component: - You can send a plain text e-mail and add an attachment using: TIdAttachment.Create(IdMessage.MessageParts, 'c:\attach.bmp'); - You can send an HTML formatted message simply by setting the IdMessage.body to the HTML string and the IdMessage.ContentType to 'text/html' However if you try to combine these, i.e. send an HTML formatted message with an attachment you will find that the message is delivered with the HTML code shown as plain text. This is because you have to send the HTML as a text part when sending attachments. So you need to create two text parts (one plain text and one HTML) and then add the attachments. Here is some example code: Notes: IdMsgSend is a TIdMessage component SMTP is a TIdSMTP component Delphi 5, Indy version is v9.03 (Indy version which ships with D6 is 8.0) var idtTextPart:TIdText; . . . IdMsgSend. Clear; IdMsgSend.ContentType := 'Multipart/Alternative'; // add a plain text message part idtTextPart:=TIdText.Create(IdMsgSend.MessageParts,nil); idtTextPart.ContentType:='text/plain'; idtTextPart.Body.Add('This is the plain part of the message.'); // add the HTML message part idtTextPart:= TIdText.Create(IdMsgSend.MessageParts,nil); idtTextPart.ContentType := 'text/html'; idtTextPart.Body.add(''); idtTextPart.Body.add('Testing...'); idtTextPart.Body.add('Testing...'); idtTextPart.Body.add('Testing...'); idtTextPart.Body.add(''); IdMsgSend.From.Address := 'me@mycompany.com'; IdMsgSend.From.Name := 'Me'; IdMsgSend.Sender.Address := 'me@mycompany.com'; IdMsgSend.Sender.Name := 'Me'; // add the recipients IdMsgSend.Recipients.clear; with IdMsgSend.Recipients.Add do Address := 'address1@somecompany.com'; with IdMsgSend.Recipients.Add do Address := 'address2@somecompany.com'; IdMsgSend.Subject := 'Some Subject'; // add an attachment TIdAttachment.Create(IdMsgSend.MessageParts, 'c:\attach.bmp'); {SMTP Setup} SMTP.Host := 'smtp.isp.com'; SMTP.Port := 25; try try {now we send the message} SMTP.Connect; SMTP.Send(IdMsgSend); except on e: Exception do ShowMessage(e.message); end; finally SMTP.Disconnect; end; showmessage('Message Sent');