Quick.SMTP.pas 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. { ***************************************************************************
  2. Copyright (c) 2016-2021 Kike P�rez
  3. Unit : Quick.SMTP
  4. Description : Send Emails
  5. Author : Kike P�rez
  6. Version : 1.5
  7. Created : 12/10/2017
  8. Modified : 08/09/2021
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.SMTP;
  22. interface
  23. {$i QuickLib.inc}
  24. uses
  25. Classes,
  26. Generics.Collections,
  27. SysUtils,
  28. IdGlobal,
  29. IdSMTP,
  30. IdMessage,
  31. IdReplySMTP,
  32. IdSSLOpenSSL,
  33. IdText,
  34. IdAttachment,
  35. IdAttachmentFile,
  36. IdAttachmentMemory,
  37. IdExplicitTLSClientServerBase,
  38. IdHTTP;
  39. type
  40. TAttachment = class
  41. private
  42. fFilename : string;
  43. fContent : TStream;
  44. public
  45. constructor Create(const aFilename : string; const aContent : TStream);
  46. destructor Destroy; override;
  47. property Filename : string read fFilename;
  48. property Content : TStream read fContent;
  49. end;
  50. TMailMessage = class
  51. private
  52. fSenderName : string;
  53. fFrom : string;
  54. fRecipient : string;
  55. fSubject : string;
  56. fBody : string;
  57. fCC : string;
  58. fBCC : string;
  59. fReplyTo : string;
  60. fBodyFromFile : Boolean;
  61. fAttachments : TStringList;
  62. fAttachmentFiles : TObjectList<TAttachment>;
  63. procedure SetBody(aValue : string);
  64. procedure SetAttachments(const Value: TStringList);
  65. public
  66. constructor Create;
  67. destructor Destroy; override;
  68. property SenderName : string read fSenderName write fSenderName;
  69. property From : string read fFrom write fFrom;
  70. property Recipient : string read fRecipient write fRecipient;
  71. property Subject : string read fSubject write fSubject;
  72. property Body : string read fBody write SetBody;
  73. property CC : string read fCC write fCC;
  74. property BCC : string read fBCC write fBCC;
  75. property ReplyTo : string read fReplyTo write fReplyTo;
  76. property Attachments : TStringList read fAttachments write SetAttachments;
  77. property AttachmentFiles : TObjectList<TAttachment> read fAttachmentFiles;
  78. procedure AddAttachment(const aFilename : string; aStream : TStream); overload;
  79. procedure AddAttachment(const aFilename, aFilePath : string); overload;
  80. procedure AddBodyFromFile(const cFileName : string);
  81. end;
  82. TSMTP = class(TIdSMTP)
  83. private
  84. fServerAuth : Boolean;
  85. fUseSSL : Boolean;
  86. fMail : TMailMessage;
  87. public
  88. constructor Create; overload;
  89. constructor Create(const cHost : string; cPort : Integer; cUseSSL : Boolean = False); overload;
  90. destructor Destroy; override;
  91. property ServerAuth : Boolean read fServerAuth write fServerAuth;
  92. property UseSSL: Boolean read fUseSSL write fUseSSL;
  93. property Mail : TMailMessage read fMail write fMail;
  94. function SendMail: Boolean; overload;
  95. function SendMail(aMail : TMailMessage) : Boolean; overload;
  96. function SendEmail(const aFromEmail,aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean; overload;
  97. function SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean; overload;
  98. function SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string; const aAttachments : TStringList) : Boolean; overload;
  99. end;
  100. implementation
  101. { TMailMessage }
  102. constructor TMailMessage.Create;
  103. begin
  104. fCC := '';
  105. fBCC := '';
  106. fBody := '';
  107. fAttachments := TStringList.Create;
  108. fAttachmentFiles := TObjectList<TAttachment>.Create(True);
  109. end;
  110. destructor TMailMessage.Destroy;
  111. begin
  112. if Assigned(fAttachments) then fAttachments.Free;
  113. if Assigned(fAttachmentFiles) then fAttachmentFiles.Free;
  114. inherited;
  115. end;
  116. procedure TMailMessage.AddAttachment(const aFilename, aFilePath : string);
  117. var
  118. fs : TFileStream;
  119. begin
  120. if not FileExists(aFilePath) then raise Exception.CreateFmt('MailMessage: file "%s" not found!',[aFilename]);
  121. fs := TFileStream.Create(aFilePath,fmOpenRead);
  122. fAttachmentFiles.Add(TAttachment.Create(aFilename,fs));
  123. end;
  124. procedure TMailMessage.AddAttachment(const aFilename : string; aStream : TStream);
  125. begin
  126. fAttachmentFiles.Add(TAttachment.Create(aFilename,aStream));
  127. end;
  128. procedure TMailMessage.AddBodyFromFile(const cFileName: string);
  129. begin
  130. fBodyFromFile := True;
  131. fBody := cFileName;
  132. end;
  133. procedure TMailMessage.SetAttachments(const Value: TStringList);
  134. begin
  135. if Assigned(fAttachments) then fAttachments.Free;
  136. fAttachments := Value;
  137. end;
  138. procedure TMailMessage.SetBody(aValue: string);
  139. begin
  140. fBodyFromFile := False;
  141. fBody := aValue;
  142. end;
  143. { TSMTP }
  144. constructor TSMTP.Create;
  145. begin
  146. inherited Create;
  147. fMail := TMailMessage.Create;
  148. Port := 25;
  149. UseTLS := TIdUseTLS.utNoTLSSupport;
  150. fUseSSL := False;
  151. end;
  152. constructor TSMTP.Create(const cHost : string; cPort : Integer; cUseSSL : Boolean = False);
  153. begin
  154. Create;
  155. Host := cHost;
  156. Port := cPort;
  157. fUseSSL := cUseSSL;
  158. end;
  159. destructor TSMTP.Destroy;
  160. begin
  161. if Assigned(fMail) then fMail.Free;
  162. inherited;
  163. end;
  164. function TSMTP.SendEmail(const aFromEmail, aFromName, aSubject, aTo, aCC, aBC, aReplyTo, aBody: string): Boolean;
  165. begin
  166. fMail.From := aFromEmail;
  167. Result := SendEmail(aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody);
  168. end;
  169. function TSMTP.SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string) : Boolean;
  170. begin
  171. Result := SendEmail(aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody,nil);
  172. end;
  173. function TSMTP.SendEmail(const aFromName,aSubject,aTo,aCC,aBC,aReplyTo,aBody : string; const aAttachments : TStringList) : Boolean;
  174. var
  175. mail : TMailMessage;
  176. begin
  177. if fMail.From.IsEmpty then raise Exception.Create('Email sender not specified!');
  178. mail := TMailMessage.Create;
  179. try
  180. Mail.From := fMail.From;
  181. if aFromName.IsEmpty then Mail.SenderName := fMail.From
  182. else Mail.SenderName := aFromName;
  183. Mail.Subject := aSubject;
  184. Mail.Body := aBody;
  185. Mail.Recipient := aTo;
  186. Mail.CC := aCC;
  187. Mail.BCC := aBC;
  188. Mail.ReplyTo := aReplyTo;
  189. if aAttachments <> nil then Mail.Attachments := aAttachments;
  190. Result := Self.SendMail(mail);
  191. finally
  192. mail.Free;
  193. end;
  194. end;
  195. function TSMTP.SendMail: Boolean;
  196. begin
  197. Result := SendMail(fMail);
  198. end;
  199. function TSMTP.SendMail(aMail : TMailMessage) : Boolean;
  200. var
  201. msg : TIdMessage;
  202. SSLHandler : TIdSSLIOHandlerSocketOpenSSL;
  203. email : string;
  204. filename : string;
  205. mBody : TIdText;
  206. idattach : TIdAttachment;
  207. attach : TAttachment;
  208. begin
  209. Result := False;
  210. SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  211. try
  212. idattach := nil;
  213. mBody := nil;
  214. msg := TIdMessage.Create(nil);
  215. try
  216. //create mail msg
  217. msg.From.Address := aMail.From;
  218. if aMail.SenderName <> '' then msg.From.Name := aMail.SenderName;
  219. msg.Subject := aMail.Subject;
  220. for email in aMail.Recipient.Split([',',';']) do msg.Recipients.Add.Address := email;
  221. for email in aMail.CC.Split([',',';']) do msg.CCList.Add.Address := email;
  222. for email in aMail.BCC.Split([',',';']) do msg.BCCList.Add.Address := email;
  223. for email in aMail.ReplyTo.Split([',',';']) do msg.ReplyTo.Add.Address := email;
  224. if aMail.fBodyFromFile then
  225. begin
  226. msg.Body.LoadFromFile(aMail.Body);
  227. end
  228. else
  229. begin
  230. mBody := TIdText.Create(msg.MessageParts);
  231. mBody.ContentType := 'text/html';
  232. mBody.CharSet:= 'utf-8';
  233. mBody.Body.Text := aMail.Body;
  234. end;
  235. //add attachements if exists
  236. if aMail.Attachments.Count > 0 then
  237. begin
  238. for filename in aMail.Attachments do
  239. begin
  240. idattach := TIdAttachmentFile.Create(msg.MessageParts,filename);
  241. end;
  242. end;
  243. //add stream attachments if exists
  244. if aMail.AttachmentFiles.Count > 0 then
  245. begin
  246. //mBody.ContentType := 'multipart/mixed';
  247. //msg.ContentType := 'multipart/mixed';
  248. for attach in aMail.AttachmentFiles do
  249. begin
  250. idattach := TIdAttachmentMemory.Create(msg.MessageParts,attach.Content);
  251. idattach.Filename := attach.Filename;
  252. end;
  253. end;
  254. //configure smtp SSL
  255. try
  256. if fUseSSL then
  257. begin
  258. Self.IOHandler := SSLHandler;
  259. SSLHandler.MaxLineAction := maException;
  260. SSLHandler.SSLOptions.Method := sslvTLSv1_2;
  261. SSLHandler.SSLOptions.Mode := sslmUnassigned;
  262. SSLHandler.SSLOptions.VerifyMode := [];
  263. SSLHandler.SSLOptions.VerifyDepth := 0;
  264. if fPort = 465 then Self.UseTLS := utUseImplicitTLS
  265. else Self.UseTLS := utUseExplicitTLS;
  266. end;
  267. //server auth
  268. if ServerAuth then Self.AuthType := TIdSMTPAuthenticationType.satDefault;
  269. Self.Port := fPort;
  270. except
  271. on E : Exception do raise Exception.Create(Format('[%s] : %s',[Self.ClassName,e.Message]));
  272. end;
  273. //send email
  274. try
  275. Self.Connect;
  276. if Self.Connected then
  277. begin
  278. Self.Send(msg);
  279. Self.Disconnect(False);
  280. Result := True;
  281. end;
  282. except
  283. on E : Exception do raise Exception.Create(Format('[%s] : %s',[Self.ClassName,e.Message]));
  284. end;
  285. finally
  286. if Assigned(idattach) then idattach.Free;
  287. if Assigned(mBody) then mBody.Free;
  288. msg.Free;
  289. end;
  290. finally
  291. SSLHandler.Free;
  292. end;
  293. end;
  294. { TAttachment }
  295. constructor TAttachment.Create(const aFilename: string; const aContent: TStream);
  296. begin
  297. fFilename := aFilename;
  298. fContent := aContent;
  299. end;
  300. destructor TAttachment.Destroy;
  301. begin
  302. if Assigned(fContent) then fContent.Free;
  303. inherited;
  304. end;
  305. end.