I'm trying to attach a PDF document to an email using Delphi (D10S) and I'd like to set the name to something other than the name of the file on the file system.
I found the following thread (from 2011) where Remy Lebeau states that you can achieve this by setting the Name
property of the TIdMessageBuilderAttachment
object when attaching them to the email using the TIdMessageBuilderHtml
:
How to name attachment files constructed by TIdMessageBuilderHtml
However, as simple as that sounds, it does not seem to work for me. The email comes through, but the attachment comes through with the original file name, not the one I've specified.
The following is a snippet of code that I expect to do as I've described but, for whatever reason, does not. In this case, I'd like the filename to come through as desired_filename.pdf
, but it comes through as undesired_filename.pdf
. I've removed the mail server credentials for obvious reasons:
procedure TForm4.Button1Click(Sender: TObject);
var
FMessageBuilder : TIdMessageBuilderHtml;
FSMTP : TIdSMTP;
FMessage : TIdMessage;
FAttachment : TIdMessageBuilderAttachment;
begin
FMessage := TIdMessage.Create();
FMessageBuilder := TIdMessageBuilderHtml.Create;
FSMTP := TIdSMTP.Create;
FAttachment := FMessageBuilder.Attachments.Add('c:\undesired_filename.pdf');
FAttachment.Name := 'desired_filename.pdf';
FMessageBuilder.FillMessage(FMessage);
FMessage.Sender.Address := '<Insert Sender Address>';
FMessage.Sender.Name := '<Insert Sender Name>';
FMessage.From.Address := '<Insert From Address>';
FMessage.From.Name := '<Insert From Name>';
FMessage.Recipients.EMailAddresses := '<Insert Recepient Address>';
FMessage.Subject := 'Attachment Test';
FSMTP.Host := '<Insert Mail Host>';
FSMTP.Username := '<Insert Username>';
FSMTP.Password := '<Insert Password>';
FSMTP.Connect;
FSMTP.Send(FMessage);
FSMTP.Disconnect;
end;
I've tested this in D10S and XE and both do the same. Any ideas what I'm doing wrong?
Using the TIdMessageBuilderAttachments.Add
overload which accepts a TStream
and setting the TIdMessageBuilderAttachment.FileName
property to the desired name does the trick for me on XE4, Indy 10.6.0.4975.
stream := TFileStream.Create('c:\undesired_filename.pdf', fmOpenRead);
FAttachment := FMessageBuilder.Attachments.Add(stream, 'application/pdf');
FAttachment.FileName := 'desired_filename.pdf';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With