Saving mail attachments

Check also Build New Mail Message
 
See the comments below:
 
procedure TForm1.Button1Click(Sender: TObject);
var
  msgNo: Integer;
begin
  //Connect to IMAP account.
  clImap.Server := 'host';
  clImap.UserName := 'user';
  clImap.Password := 'secret';
  clImap.Open();

  //Select a mailbox.
  clImap.SelectMailBox('INBOX');

  //Download a message.
  //Upon completion, the clMailMessage1SaveAttachment event handler is raised
  //per each attachment within a message.
  msgNo := 1;
  clImap.RetrieveMessage(msgNo, clMailMessage1);

  clImap.Close();
end;
 
procedure TForm1.clMailMessage1SaveAttachment(Sender: TObject;
  ABody: TclAttachmentBody; var AFileName: string; var AData: TStream;
  var Handled: Boolean);
begin
  //Some attachments don't have a file name.
  //You may need to generate a new name for such attachments.
  if (AFileName = '') then
  begin
    AFileName := IntToStr(Round(Now() * 10000000000)) + IntToStr(Random(1000)) + '.dat';
  end;
  //Provide a destination stream instance to save the attachment content to.
  AData := TFileStream.Create('C:\MyFiles\' + AFileName, fmCreate);
  //Mark the OnSaveAttachment event as handled.
  Handled := True;
end;

Feedback

Add Feedback
How can I get a list of attached files to the email?
Bogdan Pricop (April 7, 2015 at 10:12 AM)
Please use the TclMailMessage.Attachments property. For embedded images, please use another property: TclMailMessage.Images.
Sergey Shirokov (November 15, 2019 at 12:11 PM)

Add Feedback