Link to home
Start Free TrialLog in
Avatar of rainbowsoftware
rainbowsoftware

asked on

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 *)
Avatar of Mike Littlewood
Mike Littlewood
Flag of United Kingdom of Great Britain and Northern Ireland image

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
ASKER CERTIFIED SOLUTION
Avatar of Mike Littlewood
Mike Littlewood
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial