Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 897
  • Last Modified:

Attachment with MailMessage Component

I found following code for sending an e-mail with the Indy component MailMessage:

First time I send an e-mail with an attachment it is OK, but second time the e-mail sent is attached the same file twice. And the third time I send an e-mail it is attached with the same e-mail three times.

But when I close the application and send an e-mail the file is only attached once.
So why do I have do close my application to avoid the many attachments with the same file?


procedure TMailerForm.btnSendMailClick(Sender: TObject);
begin
  StatusMemo.Clear;

  //setup SMTP
  SMTP.Host := ledHost.Text;
  SMTP.Port := 25;

  //setup mail message
  MailMessage.From.Address := ledFrom.Text;
  MailMessage.Recipients.EMailAddresses := ledTo.Text + ',' + ledCC.Text;

  MailMessage.Subject := ledSubject.Text;
  MailMessage.Body.Text := Body.Text;

  if FileExists(ledAttachment.Text) then
    TIdAttachment.Create(MailMessage.MessageParts, ledAttachment.Text);

  //send mail
  try
    try
      SMTP.Connect(1000);
      SMTP.Send(MailMessage);
    except on E:Exception do
      StatusMemo.Lines.Insert(0, 'ERROR: ' + E.Message);
    end;
  finally
    if SMTP.Connected then SMTP.Disconnect;
  end;

end; (* btnSendMail Click *)
0
rainbowsoftware
Asked:
rainbowsoftware
  • 2
1 Solution
 
mikelittlewoodCommented:
You are not clearing the variable MailMessage and recreating it.
Thus everytime you get to TIdAttachment.Create(MailMessage.MessageParts, ledAttachment.Text) it is adding the attachment again
0
 
mikelittlewoodCommented:
If you dont want to clear it then maybe just use a flag to check if you have already attached the item to the mail message

  if FileExists(ledAttachment.Text) and (not bAttached) then
  begin
    TIdAttachment.Create(MailMessage.MessageParts, ledAttachment.Text);
    bAttached := True;
  end;
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now