unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdExplicitTLSClientServerBase, IdSMTP, IdSSLOpenSSL,
IdMessage, IdAttachmentFile, Vcl.StdCtrls;
type
TForm1 =
class
(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function SendEmail(sendTo: string;
subject: string;
body: string;
attachFiles: TStringList;
smtpHost: string;
smtpPort: Integer;
smtpUser: string;
smtpPass: string;
tls: TIdUseTLS): boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
SendEmail(
'mybuddy@example.com'
,
'This is the subject'
,
'This is the body of the email....'
,
nil,
'smtp.gmail.com'
,
587,
'myusername@gmail.com'
,
'mypassword'
{ 登入密碼 }, utUseExplicitTLS);
end;
function TForm1.SendEmail(sendTo, subject, body: string;
attachFiles: TStringList; smtpHost: string; smtpPort: Integer; smtpUser,
smtpPass: string; tls: TIdUseTLS): boolean;
var
smtp: TIdSmtp;
ssl: TIdSSLIOHandlerSocketOpenSSL;
msg: TIdMessage;
i: Integer;
begin
smtp:=TIdSmtp.Create(nil);
ssl:=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
msg:=TIdMessage.Create(nil);
try
try
smtp.Host:=smtpHost;
smtp.Port:=smtpPort;
smtp.Username:=smtpUser;
smtp.Password:=smtpPass;
if
not (tls=utNoTLSSupport) then begin
ssl.Destination:=smtpHost +
':'
+ IntToStr(smtpPort);
ssl.Host:=smtpHost;
ssl.Port:=smtpPort;
ssl.SSLOptions.Method:=sslvTLSv1;
smtp.IOHandler:=ssl;
smtp.UseTLS:=tls;
end;
msg.Recipients.EMailAddresses := sendTo;
msg.Subject:=subject;
msg.Body.Text:=body;
if
(Assigned(attachFiles)) then begin
for
i := 0 to attachFiles.Count - 1
do
begin
if
FileExists(attachFiles[i]) then
TIdAttachmentFile.Create(msg.MessageParts, attachFiles[i]);
end;
end;
smtp.Connect;
smtp.Send(msg);
smtp.Disconnect;
result:=
true
;
finally
msg.Free;
ssl.Free;
smtp.Free;
end;
except
result:=
false
;
end;
end;
end.