Delphi – TIdAttachment, remove path from file name of attachment

delphiemail-attachmentsindy

I am generating emails with attachments thru a Delphi program using Indy 10 and TIdAttachment. The file location/name is stored in a database table as //server/files/attachments/MyAttachment.pdf. I am attaching the file to the email as follows:

   // Add each attachment in Attachments
    for Attachment in Attachments do begin
      // Make sure file name exists before trying to add
     if FileExists(Attachment) then
       TIdAttachmentFile.Create(MessageParts, Attachment);
    end;

When I send the email the file attached is named

'__server_files_attachments_MyAttachment.pdf'.

Is there a way to remove the file path so the attachment appears as 'MyAttachment.pdf' when the recipient receives the email?

I tried using ExtractFileName() but no luck. I don't think it works as the path & file name are coming from the database as one string.

EDIT

I also tried to extract the file name itself as follows:

function GetFileName(FullPath: string): string;
var
   StrFound: TStringList;
begin
    StrFound := TStringList.Create();
    ExtractStrings(['/'], [' '], PChar(FullPath), StrFound);
    result := StrFound[StrFound.Count - 1];
end;

This returns 'MyAttachment.pdf' but this results in Delphi looking in the folder in which the program is running for the file not in '//server/files/attachments'. It appears that unless I can rename the attachment after calling TIdAttachmentFile.Create() I cannot change the file name.

EDIT – SOLUTION

Showing the solution using Remy's comments (and using GetFileName() from above):

// Add each attachment in Attachments
for Attachment in Attachments do begin
  // Make sure file name exists before trying to add
  if FileExists(Attachment) then begin
     with TIdAttachmentFile.Create(MessageParts, Attachment) do begin
       Filename := GetFileName(Attachment);
     end;
  end;
end;

Best Answer

Windows may recognize '/' as a path delimiter, but the RTL does not. Local paths and UNC paths alike must use '\' instead. You will have to normalize your filename string from '/' to '\' before passing it to Indy, such as with UnixPathToDosPath().

Related Topic