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;
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';
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
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';
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);
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;
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;
except
on E : Exception do
begin
ShowMessage('Error in the function SendEmailDelphi: ' + E.Message);
Result := False;
end;
end;
end;