Monday, 18 February 2013

How to Send Email with Attachments in Delphi XE2 using Indy Clients?

How to Send Email with Attachments in Delphi XE2 using Indy Clients?

This delphi programming language tutorial is based on sending email with attachments using indy clients in delphi XE2. Indy Clients provide TIdSMTP and TIdMessage delphi components using which we can send email easily.

First of all, you will have to declare the objects of TIdSMTP  and TIdMessage like following:

SMTP: TIdSMTP;
MailMessage: TIdMessage;

Now you have to initialize Host and Port for SMTP. You can use default emailing port as 25.

After this you have to initialize MailMessage with From Address, To Address, CC Addresses, Subject and Body of the email.
 
Lets have a look at the following very simple delphi program to send email with attachments.

function TMyForm.SendEmailDelphi : Boolean;
var
  FileName : String;
begin
  try
    Result := False;
    FileName := 'myfile.txt';
    //Setup SMTP
    SMTP := TIdSMTP.Create(nil);
    SMTP.Host := 'XXX.XXX.XXX.XXX';
    SMTP.Port := 25; //Default email port
    MailMessage.From.Address := admin@host.com;
    MailMessage.Recipients.EMailAddresses :=
TOperson@host.com + ',' + CCperson@host.com;
    MailMessage.Subject := 'Test Email from Delphi XE2';
    MailMessage.Body.Text := 'Hi! This is test email from delphi XE2';
    //Attach a file
    if FileExists(FileName) then
      TIdAttachmentFile.Create(MailMessage.MessageParts, FileName);
    //Send email
    try
      try
        SMTP.Connect;
        SMTP.Send(MailMessage);
        Result := True;
      except
        on E:Exception do
        begin
          ShowMessage('Cannot send E-Mail: ' + E.Message);
          Result := False;
        end;
      end;
    finally
      if SMTP.Connected then SMTP.Disconnect;
  end;
  except
    on E : Exception do
    begin
      ShowMessage('Error in the function SendEmailDelphi: ' + E.Message);
      Result := False;
    end;
  end;
end;

1 comment:

  1. Hello!
    Thanks for this code. In my case though I have to set
    IdMessage1.ContentType := 'text/plain';
    IdMessage1.CharSet := 'UTF-8';
    to encode "special caracters" (äöüßÄÖÜ áàéèíìóòúù ÁÀÉÈÍÌÓÒÚÙ ' " ° ^ ~ < > „hallo“ ‚oha‘ `nen) correctly.
    When doing this I cant't figure out how to setup the message to encode attachments correctly. I usuaally receive the mail where I can read:

    This is a multi-part message in MIME format

    --I=_UmZRTZ3Im2yw6NDA5yefqUgN2DWpRJ6
    Content-Type: text/plain; charset="UTF-8"
    Content-Transfer-Encoding: quoted-printable
    Content-Disposition: inline

    (this is in preview window, not only in the raw message view). Any ideas how to get it done?

    Thanks in advance,
    Klaus

    ReplyDelete