How to build a text mail message with file attachments and send it via SMTP

 
procedure TForm1.btnSendClick(Sender: TObject);
begin
  //Connecting to an SMTP service
  clSMTP1.Server := 'mail.test.com';
  clSMTP1.UserName := 'sender@test.com';
  clSMTP1.Password := 'secret';
  clSMTP1.Open();
 
  //Composing a new message
  clMailMessage1.BuildMessage('A message text follows here.', ['C:\MyFiles\MyDocument.zip']);
  clMailMessage1.From.FullAddress := 'sender@test.com';
  clMailMessage1.ToList.Add('support@mywebsite.com');
  clMailMessage1.Subject := 'Subject line';
 
  //Sending the message
  clSMTP1.Send(clMailMessage1);
 
  //Closing the connection
  clSMTP1.Close();
end;

Feedback

Add Feedback
Your sample code does not show how to add file attachments.
Homer Jones (October 11, 2018 at 9:43 PM)
The attachment is added automatically when you call the BuildMessage method and specify the attachment file path. You can specify multiple files using this method:

clMailMessage1.BuildMessage('A message text follows here.', ['C:\MyFiles\MyDocument.zip', 'C:\MyFiles\AnotherFile.docx']);

For sure, you can add attachments manually using the TclMailMessage.Bodies.AddAttachment method. But in such a case, you will have to build a valid MIME bodies structure. In case of a text-plain message with attachments, this structure is simple: one text body and some more attachment bodies. In case of a multipart-alternative message, which includes both text, HTML, inline images, etc., this structure becomes complicated. See the following article for more details:

https://www.clevercomponents.com/products/inetsuite/buildmessage.asp

Sergey Shirokov (November 15, 2019 at 11:54 AM)

Add Feedback