If you recently used the Indy component IdSmtp, it would be a shame that there was no good answer to this question. I rewrote our helper function for sending email using Indy (both HTML and plain text)
Usage example
SendHtmlEmailIndy(
'smtp.stackoverflow.com',
'Spammy McSpamerson', 'spams@example.com',
'joe@foo.net, jane@bar.net',
'john@doe.net',
'',
'Here is your sample spam e-mail',
'<!DOCTYPE html><html><body>Hello, world!</body></html>',
True,
nil);
, Indy HTML- . TIdMessageBuilderHtml ; , SmtpClient. .
procedure SendEmailIndy(
const SMTPServer: string;
const FromName, FromAddress: string;
const ToAddresses: string; //comma "," separated list of e-mail addresses
const CCAddresses: string; //comma "," separated list of e-mail addresses
const BCCAddresses: string; //comma "," separated list of e-mail addresses
const Subject: string;
const EmailBody: string;
const IsBodyHtml: Boolean; //verses Plain Text
const Attachments: TStrings);
var
smtp: TIdSMTP;
msg: TidMessage;
builder: TIdCustomMessageBuilder;
s: string;
emailAddress: string;
begin
{
Sample usage:
SendEmailIndy(
'smtp.stackoverflow.com',
'Spammy McSpamerson', 'spams@example.com',
'joe@foo.net, jane@bar.net',
'john@doe.net',
'',
'Here is your sample spam e-mail',
'<!DOCTYPE html><html><body>Hello, world!</body></html>',
True,
nil);
}
msg := TidMessage.Create(nil);
try
if IsBodyHtml then
begin
builder := TIdMessageBuilderHtml.Create;
TIdMessageBuilderHtml(builder).Html.Text := EmailBody
end
else
begin
builder := TIdMessageBuilderPlain.Create;
end;
try
if Attachments <> nil then
begin
for s in Attachments do
builder.Attachments.Add(s);
end;
builder.FillMessage(msg);
finally
builder.Free;
end;
msg.From.Name := FromName;
msg.From.Address := FromAddress;
msg.Subject := Subject;
if not IsBodyHtml then
msg.Body.Text := EmailBody;
for s in ToAddresses.Split([',']) do
begin
emailAddress := Trim(s);
if emailAddress <> '' then
begin
with msg.recipients.Add do
begin
Address := emailAddress;
end;
end;
end;
for s in CCAddresses.Split([',']) do
begin
emailAddress := Trim(s);
if emailAddress <> '' then
msg.CCList.Add.Address := emailAddress;
end;
for s in BCCAddresses.Split([',']) do
begin
emailAddress := Trim(s);
if emailAddress <> '' then
msg.BccList.Add.Address := emailAddress;
end;
smtp := TIdSMTP.Create(nil);
try
smtp.Host := SMTPServer;
smtp.Port := 25;
smtp.Connect;
try
smtp.Send(msg)
finally
smtp.Disconnect;
end;
finally
smtp.Free;
end;
finally
msg.Free;
end;
end;
. , . .