Function TForm1.SendSMTPEmailWAttachment(SenderName, SenderEmailAdress,
SenderEmailPassword, SMTPHost, SendTo, SendAsCc, SendAsBCC, ReceiptAdress,
aSubject, aBody:
String; SMTPPort: Integer;Files:TStringList): boolean;
var
IdSMTP : TiDSMTP;
IdMessage : TIdMessage;
IdText : TIDText;
IdSSLHandler : TIdSSLIOHandlerSocketOpenSSL;
IdAttachment : TIdAttachmentFile;
I : Integer;
begin
Result := FALSE;
//----------------
if (SendTo = '
')
AND (SendAsCc = '
')
AND (SendAsBCc = '
')
then exit;
//----------------
Result := True;
// --------------
//Creates
IdSMTP := TiDSMTP .Create(Application);
IdMessage := TIdMessage .Create(Application);
IdSSLHandler := TIdSSLIOHandlerSocketOpenSSL .Create(Application);
// --------------
//SSL Handler
IdSSLHandler.SSLOptions .Method := sslvSSLv23;
// sslvTLSv1;
IdSSLHandler.SSLOptions .Mode := sslmUnassigned;
IdSSLHandler.SSLOptions .VerifyMode := [];
IdSSLHandler.SSLOptions .VerifyDepth := 0;
IdSMTP .IOHandler := IdSSLHandler;
// --------------
//Prepare the MessageObject
with IdMessage
do
begin
//--------------------------------------------
ContentType := '
multipart/*';
From .Address := SenderEmailAdress;
From .
Name := SenderName;
Subject := aSubject;
Recipients .EMailAddresses := SendTo;
// To
CCList .EMailAddresses := SendAsCc;
// CC
BCCList .EMailAddresses := SendAsBCC;
// BCC
ReceiptRecipient .Text := ReceiptAdress;
// to get a receipt -> From.Text;
ReplyTo .EMailAddresses := SenderEmailAdress;
//Text/Body is within an IdText Instance
IdText := TIdText.Create(MessageParts, TStringList.Create);
IdText.ContentType := '
text/plain';
IdText.Body.Text := ABody;
end;
// --------------
//Add Attachments handed over in the TStringList called "Files"
for I:= 0
to (Files.Count -1)
do
begin
if (FileExists(Files.Strings[I]))
AND (Files.Strings[I] <> EmptyStr)
then begin
try
IdMessage.IsEncoded := True;
//----------------------------------------------
IdAttachment := TIdAttachmentFile.Create(IdMessage.MessageParts, Files.Strings[I]);
IdAttachment.FileName := ExtractFileName(Files.Strings[I]);
IdAttachment.ContentType := '
application/octet-stream';
IdAttachment.OpenLoadStream;
IdAttachment.CloseLoadStream;
finally
end;
end;
end;
// --------------
IdSMTP .Username := SenderEmailAdress;
IdSMTP .Password := SenderEmailPassword;
IdSMTP .Host := SMTPHost;
IdSMTP .Port := SMTPPort;
IdSMTP .UseTLS := utUseExplicitTLS;
// utUseRequireTLS , utUseImplicitTLS; utUseExplicitTLS
IdSMTP .AuthType := satDefault;
//---------------
//Connect & Send
Result := True;
try
IdSMTP.Connect;
IdSMTP.Send(IdMessage);
Except
Result := False;
end;
if (Result = True)
then IdSMTP.Disconnect;
// --------------
//Free memory
IdText .Free;
IdMessage .Free;
IdSSLHandler .Free;
IdSMTP .Free;
end;