pop3send.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. {==============================================================================|
  2. | Project : Ararat Synapse | 002.006.002 |
  3. |==============================================================================|
  4. | Content: POP3 client |
  5. |==============================================================================|
  6. | Copyright (c)1999-2010, Lukas Gebauer |
  7. | All rights reserved. |
  8. | |
  9. | Redistribution and use in source and binary forms, with or without |
  10. | modification, are permitted provided that the following conditions are met: |
  11. | |
  12. | Redistributions of source code must retain the above copyright notice, this |
  13. | list of conditions and the following disclaimer. |
  14. | |
  15. | Redistributions in binary form must reproduce the above copyright notice, |
  16. | this list of conditions and the following disclaimer in the documentation |
  17. | and/or other materials provided with the distribution. |
  18. | |
  19. | Neither the name of Lukas Gebauer nor the names of its contributors may |
  20. | be used to endorse or promote products derived from this software without |
  21. | specific prior written permission. |
  22. | |
  23. | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
  24. | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
  25. | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
  26. | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
  27. | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
  28. | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
  29. | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
  30. | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  31. | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
  32. | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
  33. | DAMAGE. |
  34. |==============================================================================|
  35. | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
  36. | Portions created by Lukas Gebauer are Copyright (c)2001-2010. |
  37. | All Rights Reserved. |
  38. |==============================================================================|
  39. | Contributor(s): |
  40. |==============================================================================|
  41. | History: see HISTORY.HTM from distribution package |
  42. | (Found at URL: http://www.ararat.cz/synapse/) |
  43. |==============================================================================}
  44. {:@abstract(POP3 protocol client)
  45. Used RFC: RFC-1734, RFC-1939, RFC-2195, RFC-2449, RFC-2595
  46. }
  47. {$IFDEF FPC}
  48. {$MODE DELPHI}
  49. {$ENDIF}
  50. {$H+}
  51. {$M+}
  52. {$IFDEF UNICODE}
  53. {$WARN IMPLICIT_STRING_CAST OFF}
  54. {$WARN IMPLICIT_STRING_CAST_LOSS OFF}
  55. {$ENDIF}
  56. unit pop3send;
  57. interface
  58. uses
  59. SysUtils, Classes,
  60. blcksock, synautil, synacode;
  61. const
  62. cPop3Protocol = '110';
  63. type
  64. {:The three types of possible authorization methods for "logging in" to a POP3
  65. server.}
  66. TPOP3AuthType = (POP3AuthAll, POP3AuthLogin, POP3AuthAPOP);
  67. {:@abstract(Implementation of POP3 client protocol.)
  68. Note: Are you missing properties for setting Username and Password? Look to
  69. parent @link(TSynaClient) object!
  70. Are you missing properties for specify server address and port? Look to
  71. parent @link(TSynaClient) too!}
  72. TPOP3Send = class(TSynaClient)
  73. private
  74. FSock: TTCPBlockSocket;
  75. FResultCode: Integer;
  76. FResultString: string;
  77. FFullResult: TStringList;
  78. FStatCount: Integer;
  79. FStatSize: Integer;
  80. FListSize: Integer;
  81. FTimeStamp: string;
  82. FAuthType: TPOP3AuthType;
  83. FPOP3cap: TStringList;
  84. FAutoTLS: Boolean;
  85. FFullSSL: Boolean;
  86. function ReadResult(Full: Boolean): Integer;
  87. function Connect: Boolean;
  88. function AuthLogin: Boolean;
  89. function AuthApop: Boolean;
  90. public
  91. constructor Create;
  92. destructor Destroy; override;
  93. {:You can call any custom by this method. Call Command without trailing CRLF.
  94. If MultiLine parameter is @true, multilined response are expected.
  95. Result is @true on sucess.}
  96. function CustomCommand(const Command: string; MultiLine: Boolean): boolean;
  97. {:Call CAPA command for get POP3 server capabilites.
  98. note: not all servers support this command!}
  99. function Capability: Boolean;
  100. {:Connect to remote POP3 host. If all OK, result is @true.}
  101. function Login: Boolean;
  102. {:Disconnects from POP3 server.}
  103. function Logout: Boolean;
  104. {:Send RSET command. If all OK, result is @true.}
  105. function Reset: Boolean;
  106. {:Send NOOP command. If all OK, result is @true.}
  107. function NoOp: Boolean;
  108. {:Send STAT command and fill @link(StatCount) and @link(StatSize) property.
  109. If all OK, result is @true.}
  110. function Stat: Boolean;
  111. {:Send LIST command. If Value is 0, LIST is for all messages. After
  112. successful operation is listing in FullResult. If all OK, result is @True.}
  113. function List(Value: Integer): Boolean;
  114. {:Send RETR command. After successful operation dowloaded message in
  115. @link(FullResult). If all OK, result is @true.}
  116. function Retr(Value: Integer): Boolean;
  117. {:Send RETR command. After successful operation dowloaded message in
  118. @link(Stream). If all OK, result is @true.}
  119. function RetrStream(Value: Integer; Stream: TStream): Boolean;
  120. {:Send DELE command for delete specified message. If all OK, result is @true.}
  121. function Dele(Value: Integer): Boolean;
  122. {:Send TOP command. After successful operation dowloaded headers of message
  123. and maxlines count of message in @link(FullResult). If all OK, result is
  124. @true.}
  125. function Top(Value, Maxlines: Integer): Boolean;
  126. {:Send UIDL command. If Value is 0, UIDL is for all messages. After
  127. successful operation is listing in FullResult. If all OK, result is @True.}
  128. function Uidl(Value: Integer): Boolean;
  129. {:Call STLS command for upgrade connection to SSL/TLS mode.}
  130. function StartTLS: Boolean;
  131. {:Try to find given capabily in capabilty string returned from POP3 server
  132. by CAPA command.}
  133. function FindCap(const Value: string): string;
  134. published
  135. {:Result code of last POP3 operation. 0 - error, 1 - OK.}
  136. property ResultCode: Integer read FResultCode;
  137. {:Result string of last POP3 operation.}
  138. property ResultString: string read FResultString;
  139. {:Stringlist with full lines returned as result of POP3 operation. I.e. if
  140. operation is LIST, this property is filled by list of messages. If
  141. operation is RETR, this property have downloaded message.}
  142. property FullResult: TStringList read FFullResult;
  143. {:After STAT command is there count of messages in inbox.}
  144. property StatCount: Integer read FStatCount;
  145. {:After STAT command is there size of all messages in inbox.}
  146. property StatSize: Integer read FStatSize;
  147. {:After LIST 0 command size of all messages on server, After LIST x size of message x on server}
  148. property ListSize: Integer read FListSize;
  149. {:If server support this, after comnnect is in this property timestamp of
  150. remote server.}
  151. property TimeStamp: string read FTimeStamp;
  152. {:Type of authorisation for login to POP3 server. Dafault is autodetect one
  153. of possible authorisation. Autodetect do this:
  154. If remote POP3 server support APOP, try login by APOP method. If APOP is
  155. not supported, or if APOP login failed, try classic USER+PASS login method.}
  156. property AuthType: TPOP3AuthType read FAuthType Write FAuthType;
  157. {:If is set to @true, then upgrade to SSL/TLS mode if remote server support it.}
  158. property AutoTLS: Boolean read FAutoTLS Write FAutoTLS;
  159. {:SSL/TLS mode is used from first contact to server. Servers with full
  160. SSL/TLS mode usualy using non-standard TCP port!}
  161. property FullSSL: Boolean read FFullSSL Write FFullSSL;
  162. {:Socket object used for TCP/IP operation. Good for seting OnStatus hook, etc.}
  163. property Sock: TTCPBlockSocket read FSock;
  164. end;
  165. implementation
  166. constructor TPOP3Send.Create;
  167. begin
  168. inherited Create;
  169. FFullResult := TStringList.Create;
  170. FPOP3cap := TStringList.Create;
  171. FSock := TTCPBlockSocket.Create;
  172. FSock.Owner := self;
  173. FSock.ConvertLineEnd := true;
  174. FTimeout := 60000;
  175. FTargetPort := cPop3Protocol;
  176. FStatCount := 0;
  177. FStatSize := 0;
  178. FListSize := 0;
  179. FAuthType := POP3AuthAll;
  180. FAutoTLS := False;
  181. FFullSSL := False;
  182. end;
  183. destructor TPOP3Send.Destroy;
  184. begin
  185. FSock.Free;
  186. FPOP3cap.Free;
  187. FullResult.Free;
  188. inherited Destroy;
  189. end;
  190. function TPOP3Send.ReadResult(Full: Boolean): Integer;
  191. var
  192. s: string;
  193. begin
  194. Result := 0;
  195. FFullResult.Clear;
  196. s := FSock.RecvString(FTimeout);
  197. if Pos('+OK', s) = 1 then
  198. Result := 1;
  199. FResultString := s;
  200. if Full and (Result = 1) then
  201. repeat
  202. s := FSock.RecvString(FTimeout);
  203. if s = '.' then
  204. Break;
  205. if s <> '' then
  206. if s[1] = '.' then
  207. Delete(s, 1, 1);
  208. FFullResult.Add(s);
  209. until FSock.LastError <> 0;
  210. if not Full and (Result = 1) then
  211. FFullResult.Add(SeparateRight(FResultString, ' '));
  212. if FSock.LastError <> 0 then
  213. Result := 0;
  214. FResultCode := Result;
  215. end;
  216. function TPOP3Send.CustomCommand(const Command: string; MultiLine: Boolean): boolean;
  217. begin
  218. FSock.SendString(Command + CRLF);
  219. Result := ReadResult(MultiLine) <> 0;
  220. end;
  221. function TPOP3Send.AuthLogin: Boolean;
  222. begin
  223. Result := False;
  224. if not CustomCommand('USER ' + FUserName, False) then
  225. exit;
  226. Result := CustomCommand('PASS ' + FPassword, False)
  227. end;
  228. function TPOP3Send.AuthAPOP: Boolean;
  229. var
  230. s: string;
  231. begin
  232. s := StrToHex(MD5(FTimeStamp + FPassWord));
  233. Result := CustomCommand('APOP ' + FUserName + ' ' + s, False);
  234. end;
  235. function TPOP3Send.Connect: Boolean;
  236. begin
  237. // Do not call this function! It is calling by LOGIN method!
  238. FStatCount := 0;
  239. FStatSize := 0;
  240. FSock.CloseSocket;
  241. FSock.LineBuffer := '';
  242. FSock.Bind(FIPInterface, cAnyPort);
  243. if FSock.LastError = 0 then
  244. FSock.Connect(FTargetHost, FTargetPort);
  245. if FSock.LastError = 0 then
  246. if FFullSSL then
  247. FSock.SSLDoConnect;
  248. Result := FSock.LastError = 0;
  249. end;
  250. function TPOP3Send.Capability: Boolean;
  251. begin
  252. FPOP3cap.Clear;
  253. Result := CustomCommand('CAPA', True);
  254. if Result then
  255. FPOP3cap.AddStrings(FFullResult);
  256. end;
  257. function TPOP3Send.Login: Boolean;
  258. var
  259. s, s1: string;
  260. begin
  261. Result := False;
  262. FTimeStamp := '';
  263. if not Connect then
  264. Exit;
  265. if ReadResult(False) <> 1 then
  266. Exit;
  267. s := SeparateRight(FResultString, '<');
  268. if s <> FResultString then
  269. begin
  270. s1 := Trim(SeparateLeft(s, '>'));
  271. if s1 <> s then
  272. FTimeStamp := '<' + s1 + '>';
  273. end;
  274. Result := False;
  275. if Capability then
  276. if FAutoTLS and (Findcap('STLS') <> '') then
  277. if StartTLS then
  278. Capability
  279. else
  280. begin
  281. Result := False;
  282. Exit;
  283. end;
  284. if (FTimeStamp <> '') and not (FAuthType = POP3AuthLogin) then
  285. begin
  286. Result := AuthApop;
  287. if not Result then
  288. begin
  289. if not Connect then
  290. Exit;
  291. if ReadResult(False) <> 1 then
  292. Exit;
  293. end;
  294. end;
  295. if not Result and not (FAuthType = POP3AuthAPOP) then
  296. Result := AuthLogin;
  297. end;
  298. function TPOP3Send.Logout: Boolean;
  299. begin
  300. Result := CustomCommand('QUIT', False);
  301. FSock.CloseSocket;
  302. end;
  303. function TPOP3Send.Reset: Boolean;
  304. begin
  305. Result := CustomCommand('RSET', False);
  306. end;
  307. function TPOP3Send.NoOp: Boolean;
  308. begin
  309. Result := CustomCommand('NOOP', False);
  310. end;
  311. function TPOP3Send.Stat: Boolean;
  312. var
  313. s: string;
  314. begin
  315. Result := CustomCommand('STAT', False);
  316. if Result then
  317. begin
  318. s := SeparateRight(ResultString, '+OK ');
  319. FStatCount := StrToIntDef(Trim(SeparateLeft(s, ' ')), 0);
  320. FStatSize := StrToIntDef(Trim(SeparateRight(s, ' ')), 0);
  321. end;
  322. end;
  323. function TPOP3Send.List(Value: Integer): Boolean;
  324. var
  325. s: string;
  326. n: integer;
  327. begin
  328. if Value = 0 then
  329. s := 'LIST'
  330. else
  331. s := 'LIST ' + IntToStr(Value);
  332. Result := CustomCommand(s, Value = 0);
  333. FListSize := 0;
  334. if Result then
  335. if Value <> 0 then
  336. begin
  337. s := SeparateRight(ResultString, '+OK ');
  338. FListSize := StrToIntDef(SeparateLeft(SeparateRight(s, ' '), ' '), 0);
  339. end
  340. else
  341. for n := 0 to FFullResult.Count - 1 do
  342. FListSize := FListSize + StrToIntDef(SeparateLeft(SeparateRight(s, ' '), ' '), 0);
  343. end;
  344. function TPOP3Send.Retr(Value: Integer): Boolean;
  345. begin
  346. Result := CustomCommand('RETR ' + IntToStr(Value), True);
  347. end;
  348. //based on code by Miha Vrhovnik
  349. function TPOP3Send.RetrStream(Value: Integer; Stream: TStream): Boolean;
  350. var
  351. s: string;
  352. begin
  353. Result := False;
  354. FFullResult.Clear;
  355. Stream.Size := 0;
  356. FSock.SendString('RETR ' + IntToStr(Value) + CRLF);
  357. s := FSock.RecvString(FTimeout);
  358. if Pos('+OK', s) = 1 then
  359. Result := True;
  360. FResultString := s;
  361. if Result then begin
  362. repeat
  363. s := FSock.RecvString(FTimeout);
  364. if s = '.' then
  365. Break;
  366. if s <> '' then begin
  367. if s[1] = '.' then
  368. Delete(s, 1, 1);
  369. end;
  370. WriteStrToStream(Stream, s);
  371. WriteStrToStream(Stream, CRLF);
  372. until FSock.LastError <> 0;
  373. end;
  374. if Result then
  375. FResultCode := 1
  376. else
  377. FResultCode := 0;
  378. end;
  379. function TPOP3Send.Dele(Value: Integer): Boolean;
  380. begin
  381. Result := CustomCommand('DELE ' + IntToStr(Value), False);
  382. end;
  383. function TPOP3Send.Top(Value, Maxlines: Integer): Boolean;
  384. begin
  385. Result := CustomCommand('TOP ' + IntToStr(Value) + ' ' + IntToStr(Maxlines), True);
  386. end;
  387. function TPOP3Send.Uidl(Value: Integer): Boolean;
  388. var
  389. s: string;
  390. begin
  391. if Value = 0 then
  392. s := 'UIDL'
  393. else
  394. s := 'UIDL ' + IntToStr(Value);
  395. Result := CustomCommand(s, Value = 0);
  396. end;
  397. function TPOP3Send.StartTLS: Boolean;
  398. begin
  399. Result := False;
  400. if CustomCommand('STLS', False) then
  401. begin
  402. Fsock.SSLDoConnect;
  403. Result := FSock.LastError = 0;
  404. end;
  405. end;
  406. function TPOP3Send.FindCap(const Value: string): string;
  407. var
  408. n: Integer;
  409. s: string;
  410. begin
  411. s := UpperCase(Value);
  412. Result := '';
  413. for n := 0 to FPOP3cap.Count - 1 do
  414. if Pos(s, UpperCase(FPOP3cap[n])) = 1 then
  415. begin
  416. Result := FPOP3cap[n];
  417. Break;
  418. end;
  419. end;
  420. end.