PageRenderTime 63ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/module/ASC.MailSystem/ClassLibrary/ActiveUp.Net.Pop3/Pop3Client.cs

https://github.com/dc0d/ONLYOFFICE-Server
C# | 2155 lines | 1070 code | 190 blank | 895 comment | 70 complexity | 4016836d8ccda65ebbbc13862b8fb4fb MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception
  1. // Copyright 2001-2010 - Active Up SPRLU (http://www.agilecomponents.com)
  2. //
  3. // This file is part of MailSystem.NET.
  4. // MailSystem.NET is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation; either version 2 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // MailSystem.NET is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. // You should have received a copy of the GNU Lesser General Public License
  14. // along with SharpMap; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. using System;
  17. using System.Text.RegularExpressions;
  18. using ActiveUp.Net.Security;
  19. namespace ActiveUp.Net.Mail
  20. {
  21. #region Pop3Client Object version 2
  22. /// <summary>
  23. /// POP3 Client extending a System.Net.Sockets.TcpClient to send/receive POP3 command/responses.
  24. /// </summary>
  25. #if !PocketPC
  26. [System.Serializable]
  27. #endif
  28. public class Pop3Client : ActiveUp.Net.Common.BaseProtocolClient
  29. {
  30. #region Constructors
  31. /// <summary>
  32. /// Default constructor
  33. /// </summary>
  34. public Pop3Client()
  35. {
  36. }
  37. #if PocketPC
  38. /// <summary>
  39. /// Finds PPC Encoding replacing ISO 8859-1 as standard.
  40. /// </summary>
  41. internal static System.Text.Encoding PPCEncode
  42. {
  43. get
  44. {
  45. //Since ISO 8859-1, not supported widelys (Depends on PPC region)
  46. //We are using Windows Code Page 1252 which is very much nearer to ISO
  47. //standard.
  48. return System.Text.Encoding.GetEncoding(1252);
  49. }
  50. }
  51. #endif
  52. #endregion
  53. #region Events
  54. #region Event definitions
  55. /*/// <summary>
  56. /// Event fired when a certain amount of bytes are read during message or Header retrieval.
  57. /// </summary>
  58. public event ActiveUp.Net.Mail.ProgressEventHandler Progress;*/
  59. /// <summary>
  60. /// Event fired when authentication starts.
  61. /// </summary>
  62. public event ActiveUp.Net.Mail.AuthenticatingEventHandler Authenticating;
  63. /// <summary>
  64. /// Event fired when authentication completed.
  65. /// </summary>
  66. public event ActiveUp.Net.Mail.AuthenticatedEventHandler Authenticated;
  67. /// <summary>
  68. /// Event fired when NOOP command is issued.
  69. /// </summary>
  70. public event ActiveUp.Net.Mail.NoopingEventHandler Nooping;
  71. /// <summary>
  72. /// Event fired when NOOP command completed.
  73. /// </summary>
  74. public event ActiveUp.Net.Mail.NoopedEventHandler Nooped;
  75. /// <summary>
  76. /// Event fired when a command is being written to the server.
  77. /// </summary>
  78. public event ActiveUp.Net.Mail.TcpWritingEventHandler TcpWriting;
  79. /// <summary>
  80. /// Event fired when a command has been written to the server.
  81. /// </summary>
  82. public event ActiveUp.Net.Mail.TcpWrittenEventHandler TcpWritten;
  83. /// <summary>
  84. /// Event fired when a response is being read from the server.
  85. /// </summary>
  86. public event ActiveUp.Net.Mail.TcpReadingEventHandler TcpReading;
  87. /// <summary>
  88. /// Event fired when a response has been read from the server.
  89. /// </summary>
  90. public event ActiveUp.Net.Mail.TcpReadEventHandler TcpRead;
  91. /// <summary>
  92. /// Event fired when a message is being requested using the RetrieveMessage() method.
  93. /// </summary>
  94. public event ActiveUp.Net.Mail.MessageRetrievingEventHandler MessageRetrieving;
  95. /// <summary>
  96. /// Event fired when a message is being retrieved using the RetrieveMessage() method.
  97. /// </summary>
  98. public event ActiveUp.Net.Mail.MessageRetrievedEventHandler MessageRetrieved;
  99. /// <summary>
  100. /// Event fired when a message Header is being requested using the RetrieveHeader() method.
  101. /// </summary>
  102. public event ActiveUp.Net.Mail.HeaderRetrievingEventHandler HeaderRetrieving;
  103. /// <summary>
  104. /// Event fired when a message Header has been retrieved using the RetrieveHeader() method.
  105. /// </summary>
  106. public event ActiveUp.Net.Mail.HeaderRetrievedEventHandler HeaderRetrieved;
  107. /// <summary>
  108. /// Event fired when attempting to connect to the remote server using the specified host.
  109. /// </summary>
  110. public event ActiveUp.Net.Mail.ConnectingEventHandler Connecting;
  111. /// <summary>
  112. /// Event fired when the object is connected to the remote server or when connection failed.
  113. /// </summary>
  114. public new event ActiveUp.Net.Mail.ConnectedEventHandler Connected;
  115. /// <summary>
  116. /// Event fired when attempting to disconnect from the remote server.
  117. /// </summary>
  118. public event ActiveUp.Net.Mail.DisconnectingEventHandler Disconnecting;
  119. /// <summary>
  120. /// Event fired when the object disconnected from the remote server.
  121. /// </summary>
  122. public event ActiveUp.Net.Mail.DisconnectedEventHandler Disconnected;
  123. #endregion
  124. #region Event triggers and logging
  125. /*internal void OnProgress(ActiveUp.Net.Mail.ProgressEventArgs e)
  126. {
  127. if(Progress!=null) Progress(this,e);
  128. }*/
  129. internal void OnAuthenticating(ActiveUp.Net.Mail.AuthenticatingEventArgs e)
  130. {
  131. if (Authenticating != null) Authenticating(this, e);
  132. ActiveUp.Net.Mail.Logger.AddEntry("Authenticating as " + e.Username + " on " + e.Host + "...", 2);
  133. }
  134. internal void OnAuthenticated(ActiveUp.Net.Mail.AuthenticatedEventArgs e)
  135. {
  136. if (Authenticated != null) Authenticated(this, e);
  137. ActiveUp.Net.Mail.Logger.AddEntry("Authenticated as " + e.Username + " on " + e.Host + ".", 2);
  138. }
  139. internal void OnNooping()
  140. {
  141. if (Nooping != null) Nooping(this);
  142. ActiveUp.Net.Mail.Logger.AddEntry("Nooping...", 1);
  143. }
  144. internal void OnNooped()
  145. {
  146. if (Nooped != null) Nooped(this);
  147. ActiveUp.Net.Mail.Logger.AddEntry("Nooped.", 1);
  148. }
  149. internal void OnTcpWriting(ActiveUp.Net.Mail.TcpWritingEventArgs e)
  150. {
  151. if (TcpWriting != null) TcpWriting(this, e);
  152. ActiveUp.Net.Mail.Logger.AddEntry("Sending " + e.Command + "...", 1);
  153. }
  154. internal void OnTcpWritten(ActiveUp.Net.Mail.TcpWrittenEventArgs e)
  155. {
  156. if (TcpWritten != null) TcpWritten(this, e);
  157. ActiveUp.Net.Mail.Logger.AddEntry("Sent " + e.Command + ".", 1);
  158. }
  159. internal void OnTcpReading()
  160. {
  161. if (TcpReading != null) TcpReading(this);
  162. ActiveUp.Net.Mail.Logger.AddEntry("Reading...", 1);
  163. }
  164. internal void OnTcpRead(ActiveUp.Net.Mail.TcpReadEventArgs e)
  165. {
  166. if (TcpRead != null) TcpRead(this, e);
  167. ActiveUp.Net.Mail.Logger.AddEntry("Read " + e.Response + ".", 1);
  168. }
  169. internal void OnMessageRetrieving(ActiveUp.Net.Mail.MessageRetrievingEventArgs e)
  170. {
  171. if (MessageRetrieving != null) MessageRetrieving(this, e);
  172. ActiveUp.Net.Mail.Logger.AddEntry("Retrieving message at index " + e.MessageIndex + " out of " + e.TotalCount + "...", 2);
  173. }
  174. internal void OnMessageRetrieved(ActiveUp.Net.Mail.MessageRetrievedEventArgs e)
  175. {
  176. if (MessageRetrieved != null) MessageRetrieved(this, e);
  177. ActiveUp.Net.Mail.Logger.AddEntry("Retrieved message at index " + e.MessageIndex + " out of " + e.TotalCount + ".", 2);
  178. }
  179. internal void OnHeaderRetrieving(ActiveUp.Net.Mail.HeaderRetrievingEventArgs e)
  180. {
  181. if (HeaderRetrieving != null) HeaderRetrieving(this, e);
  182. ActiveUp.Net.Mail.Logger.AddEntry("Retrieving Header at index " + e.MessageIndex + " out of " + e.TotalCount + "...", 2);
  183. }
  184. internal void OnHeaderRetrieved(ActiveUp.Net.Mail.HeaderRetrievedEventArgs e)
  185. {
  186. if (HeaderRetrieved != null) HeaderRetrieved(this, e);
  187. ActiveUp.Net.Mail.Logger.AddEntry("Retrieved Header at index " + e.MessageIndex + " out of " + e.TotalCount + ".", 2);
  188. }
  189. internal void OnDisconnecting()
  190. {
  191. if (Disconnecting != null) Disconnecting(this);
  192. ActiveUp.Net.Mail.Logger.AddEntry("Disconnecting...", 2);
  193. }
  194. internal void OnDisconnected(ActiveUp.Net.Mail.DisconnectedEventArgs e)
  195. {
  196. if (Disconnected != null) Disconnected(this, e);
  197. ActiveUp.Net.Mail.Logger.AddEntry("Disconnected.", 2);
  198. }
  199. internal void OnConnecting()
  200. {
  201. if (Connecting != null) Connecting(this);
  202. ActiveUp.Net.Mail.Logger.AddEntry("Connecting...", 2);
  203. }
  204. internal void OnConnected(ActiveUp.Net.Mail.ConnectedEventArgs e)
  205. {
  206. if (Connected != null) Connected(this, e);
  207. ActiveUp.Net.Mail.Logger.AddEntry("Connected. Server replied : " + e.ServerResponse + ".", 2);
  208. }
  209. #endregion
  210. #endregion
  211. #region Private fields
  212. int _messageCount;
  213. long _totalSize;
  214. //#if !PocketPC
  215. // System.Net.Security.SslStream _sslStream;
  216. //#endif
  217. #endregion
  218. #region Properties
  219. /// <summary>
  220. /// Number of messages on the remote POP server.
  221. /// </summary>
  222. /// <example>
  223. /// <code>
  224. /// C#
  225. ///
  226. /// Pop3Client pop = new Pop3Client();
  227. /// pop.Connect("mail.myhost.com","user","pass");
  228. /// int msgCount = pop.MessageCount;
  229. /// pop.Disconnect();
  230. ///
  231. /// VB.NET
  232. ///
  233. /// Dim pop As New Pop3Client
  234. /// pop.Connect("mail.myhost.com","user","pass")
  235. /// Dim msgCount as Integer = pop.MessageCount
  236. /// pop.Disconnect()
  237. ///
  238. /// JScript.NET
  239. ///
  240. /// var pop:Pop3Client = new Pop3Client();
  241. /// pop.Connect("mail.myhost.com","user","pass");
  242. /// var msgCount:int = pop.MessageCount;
  243. /// pop.Disconnect();
  244. /// </code>
  245. /// </example>
  246. public int MessageCount
  247. {
  248. get
  249. {
  250. return this._messageCount;
  251. }
  252. set
  253. {
  254. this._messageCount = value;
  255. }
  256. }
  257. /// <summary>
  258. /// Size of all messages on the remote POP server.
  259. /// </summary>
  260. /// <example>
  261. /// <code>
  262. /// C#
  263. ///
  264. /// Pop3Client pop = new Pop3Client();
  265. /// pop.Connect("mail.myhost.com","user","pass");
  266. /// int accountSize = pop.TotalSize;
  267. /// pop.Disconnect();
  268. ///
  269. /// VB.NET
  270. ///
  271. /// Dim pop As New Pop3Client
  272. /// pop.Connect("mail.myhost.com","user","pass")
  273. /// Dim accountSize as Integer = pop.TotalSize
  274. /// pop.Disconnect()
  275. ///
  276. /// JScript.NET
  277. ///
  278. /// var pop:Pop3Client = new Pop3Client();
  279. /// pop.Connect("mail.myhost.com","user","pass");
  280. /// var accountSize:int = pop.TotalSize;
  281. /// pop.Disconnect();
  282. /// </code>
  283. /// </example>
  284. public long TotalSize
  285. {
  286. get
  287. {
  288. return this._totalSize;
  289. }
  290. set
  291. {
  292. this._totalSize = value;
  293. }
  294. }
  295. #endregion
  296. #region Delegates and associated private fields
  297. private delegate string DelegateConnect(string host, int port);
  298. private DelegateConnect _delegateConnect;
  299. private delegate string DelegateConnectIPAddress(System.Net.IPAddress addr, int port);
  300. private DelegateConnectIPAddress _delegateConnectIPAddress;
  301. private delegate string DelegateConnectIPAddresses(System.Net.IPAddress[] addresses, int port);
  302. private DelegateConnectIPAddresses _delegateConnectIPAddresses;
  303. private delegate string DelegateConnectAuth(string host, int port, string user, string pass);
  304. private DelegateConnectAuth _delegateConnectAuth;
  305. private delegate string DelegateConnectAPOP(string host, int port, string user, string pass);
  306. private DelegateConnectAPOP _delegateConnectAPOP;
  307. #if !PocketPC
  308. private delegate string DelegateConnectSslAuth(string host, int port, string username, string password, ActiveUp.Net.Security.SslHandShake sslHandShake);
  309. private DelegateConnectSslAuth _delegateConnectSslAuth;
  310. private delegate string DelegateConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  311. private DelegateConnectSsl _delegateConnectSsl;
  312. private delegate string DelegateConnectSslIPAddress(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  313. private DelegateConnectSslIPAddress _delegateConnectSslIPAddress;
  314. private delegate string DelegateConnectSslIPAddresses(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  315. private DelegateConnectSslIPAddresses _delegateConnectSslIPAddresses;
  316. #endif
  317. private delegate string DelegateAuthenticate(string username, string password, SaslMechanism mechanism);
  318. private DelegateAuthenticate _delegateAuthenticate;
  319. private delegate string DelegateDisconnect();
  320. private DelegateDisconnect _delegateDisconnect;
  321. private delegate string DelegateCommand(string command);
  322. private DelegateCommand _delegateCommand;
  323. private delegate byte[] DelegateRetrieveMessage(int messageIndex, bool deleteMessage);
  324. private DelegateRetrieveMessage _delegateRetrieveMessage;
  325. private delegate Message DelegateRetrieveMessageObject(int messageIndex, bool deleteMessage);
  326. private DelegateRetrieveMessageObject _delegateRetrieveMessageObject;
  327. private delegate void DelegateStoreMessage(int messageIndex, bool deleteMessage, string destinationPath);
  328. private DelegateStoreMessage _delegateStoreMessage;
  329. private delegate byte[] DelegateRetrieveHeader(int messageIndex, int numberOfBodyLines);
  330. private DelegateRetrieveHeader _delegateRetrieveHeader;
  331. private delegate Header DelegateRetrieveHeaderObject(int messageIndex);
  332. private DelegateRetrieveHeaderObject _delegateRetrieveHeaderObject;
  333. private delegate void DelegateStoreHeader(int messageIndex, string destinationPath);
  334. private DelegateStoreHeader _delegateStoreHeader;
  335. private delegate void DelegateDeleteMessage(int indexOnServer);
  336. private DelegateDeleteMessage _delegateDeleteMessage;
  337. private delegate int DelegateReset();
  338. private DelegateReset _delegateReset;
  339. private delegate string DelegateGetUniqueID(int messageIndex);
  340. private DelegateGetUniqueID _delegateGetUniqueID;
  341. private delegate System.Collections.Generic.List<PopServerUniqueId> DelegateGetUniqueIDs();
  342. private DelegateGetUniqueIDs _delegateGetUniqueIDs;
  343. private delegate int DelegateGetMessageSize(int messageIndex);
  344. private DelegateGetMessageSize _delegateGetMessageSize;
  345. private delegate void DelegateUpdateStats();
  346. private DelegateUpdateStats _delegateUpdateStats;
  347. private delegate void DelegateNoop();
  348. private DelegateNoop _delegateNoop;
  349. private delegate bool DelegateCheckAPOP(string host, int port);
  350. private static DelegateCheckAPOP _delegateCheckAPOP;
  351. private delegate bool DelegateCheckAPOPString(string host);
  352. private static DelegateCheckAPOPString _delegateCheckAPOPString;
  353. private delegate string[] DelegateGetServerCapabilities();
  354. private DelegateGetServerCapabilities _delegateGetServerCapabilities;
  355. #endregion
  356. #region Methods
  357. #region Private utility methods
  358. #if !PocketPC
  359. protected override void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
  360. {
  361. this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false, sslHandShake.ServerCertificateValidationCallback, sslHandShake.ClientCertificateSelectionCallback);
  362. this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
  363. }
  364. #endif
  365. private string _CramMd5(string username, string password)
  366. {
  367. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password));
  368. //string digest = System.Text.Encoding.ASCII.GetString(System.Convert.FromBase64String(this.Command("auth cram-md5").Split(' ')[1].Trim(new char[] { '\r', '\n' })));
  369. byte[] data = System.Convert.FromBase64String(this.Command("auth cram-md5").Split(' ')[1].Trim(new char[] { '\r', '\n' }));
  370. #if !PocketPC
  371. string digest = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(data,0,data.Length);
  372. string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(username + " " + ActiveUp.Net.Mail.Crypto.HMACMD5Digest(password, digest))));
  373. #else
  374. string digest = PPCEncode.GetString(data, 0, data.Length);
  375. string response = this.Command(System.Convert.ToBase64String(PPCEncode.GetBytes(username + " " + ActiveUp.Net.Mail.Crypto.HMACMD5Digest(password, digest))));
  376. #endif
  377. //string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username + " " + ActiveUp.Net.Mail.Crypto.HMACMD5Digest(password, digest))));
  378. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, response));
  379. return response;
  380. }
  381. public override string Login(string user, string pass, string host)
  382. {
  383. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(user, pass, host));
  384. string response = this.Command("USER " + user);
  385. string presponse = this.Command("PASS " + pass);
  386. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(user, pass, host, response));
  387. /*response = this.Command("STAT");
  388. var splited = response.Split(' ');
  389. this._messageCount = System.Convert.ToInt32(splited[1]);
  390. this._totalSize = System.Convert.ToInt32(splited[2]);*/
  391. return presponse;
  392. }
  393. private string _Login(string username, string password)
  394. {
  395. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password));
  396. this.Command("auth login");
  397. //this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username)));
  398. //string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(password)));
  399. #if !PocketPC
  400. this.Command(System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(username)));
  401. string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(password)));
  402. #else
  403. this.Command(System.Convert.ToBase64String(PPCEncode.GetBytes(username)));
  404. string response = this.Command(System.Convert.ToBase64String(PPCEncode.GetBytes(password)));
  405. #endif
  406. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, response));
  407. return response;
  408. }
  409. private string ReadLine()
  410. {
  411. this.OnTcpReading();
  412. //System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.ASCII);
  413. #if !PocketPC
  414. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
  415. #else
  416. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), PPCEncode);
  417. #endif
  418. string response = sr.ReadLine();
  419. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs(response));
  420. return response;
  421. }
  422. private string StoreToFile(string path, byte[] data)
  423. {
  424. System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
  425. fs.Write(data, 0, data.Length);
  426. fs.Close();
  427. return path;
  428. }
  429. private System.IO.MemoryStream StoreToStream(byte[] data)
  430. {
  431. return new System.IO.MemoryStream(data, 0, data.Length, false, true);
  432. }
  433. #if PocketPC
  434. /// <summary>
  435. /// This functions Injects Sleep wherever required in PocketPC. This is required so that
  436. /// Less powerful MessagePump in PocketPC gets chance to execute other things.
  437. /// </summary>
  438. private void PPCSleep()
  439. {
  440. System.Threading.Thread.Sleep(1);
  441. }
  442. #endif
  443. #endregion
  444. #region Public methods
  445. #region Connecting, authenticating and disconnecting
  446. #region Cleartext methods
  447. /// <summary>
  448. /// Connects the object with the remote POP server using the given parameters.
  449. /// </summary>
  450. /// <param name="host">Remote POP server address.</param>
  451. /// <returns>The server's welcome greeting.</returns>
  452. /// <example>
  453. /// <code>
  454. /// C#
  455. ///
  456. /// Pop3Client pop = new Pop3Client();
  457. /// pop.Connect("mail.myhost.com");
  458. ///
  459. /// VB.NET
  460. ///
  461. /// Dim pop As New Pop3Client
  462. /// pop.Connect("mail.myhost.com")
  463. ///
  464. /// JScript.NET
  465. ///
  466. /// var pop:Pop3Client = new Pop3Client();
  467. /// pop.Connect("mail.myhost.com");
  468. /// </code>
  469. /// </example>
  470. public string Connect(string host)
  471. {
  472. return this.Connect(host, 110);
  473. }
  474. public IAsyncResult BeginConnect(string host, AsyncCallback callback)
  475. {
  476. return this.BeginConnect(host, 110, callback);
  477. }
  478. /// <summary>
  479. /// Connects the object with the remote POP server using the given parameters.
  480. /// </summary>
  481. /// <param name="host">Remote POP server address.</param>
  482. /// <param name="port">The port to be used.</param>
  483. /// <returns>The server's welcome greeting.</returns>
  484. /// <example>
  485. /// <code>
  486. /// C#
  487. ///
  488. /// Pop3Client pop = new Pop3Client();
  489. /// pop.Connect("mail.myhost.com",8503);
  490. ///
  491. /// VB.NET
  492. ///
  493. /// Dim pop As New Pop3Client
  494. /// pop.Connect("mail.myhost.com",8503)
  495. ///
  496. /// JScript.NET
  497. ///
  498. /// var pop:Pop3Client = new Pop3Client();
  499. /// pop.Connect("mail.myhost.com",8503);
  500. /// </code>
  501. /// </example>
  502. public new string Connect(string host, int port)
  503. {
  504. this.OnConnecting();
  505. base.Connect(host, port);
  506. string response = "";
  507. response = this.ReadLine();
  508. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  509. return response;
  510. }
  511. public string ConnectTLS(string host, int port)
  512. {
  513. this.Connect(host, port);
  514. return this.StartTLS(host);
  515. }
  516. public override IAsyncResult BeginConnect(string host, int port, AsyncCallback callback)
  517. {
  518. this._delegateConnect = this.Connect;
  519. return this._delegateConnect.BeginInvoke(host, port, callback, this._delegateConnect);
  520. }
  521. public IAsyncResult BeginConnectTLS(string host, int port, AsyncCallback callback)
  522. {
  523. this._delegateConnect = this.ConnectTLS;
  524. return this._delegateConnect.BeginInvoke(host, port, callback, this._delegateConnect);
  525. }
  526. public new string Connect(System.Net.IPAddress addr, int port)
  527. {
  528. this.OnConnecting();
  529. base.Connect(addr, port);
  530. string response = "";
  531. response = this.ReadLine();
  532. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  533. return response;
  534. }
  535. public IAsyncResult BeginConnect(System.Net.IPAddress addr, int port, AsyncCallback callback)
  536. {
  537. this._delegateConnectIPAddress = this.Connect;
  538. return this._delegateConnectIPAddress.BeginInvoke(addr, port, callback, this._delegateConnectIPAddress);
  539. }
  540. public new string Connect(System.Net.IPAddress[] addresses, int port)
  541. {
  542. this.OnConnecting();
  543. #if !PocketPC
  544. base.Connect(addresses, port);
  545. #else
  546. if(addresses.Length>0)
  547. base.Connect(addresses[0], port);
  548. PPCSleep();
  549. #endif
  550. string response = "";
  551. response = this.ReadLine();
  552. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  553. return response;
  554. }
  555. public IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, AsyncCallback callback)
  556. {
  557. this._delegateConnectIPAddresses = this.Connect;
  558. return this._delegateConnectIPAddresses.BeginInvoke(addresses, port, callback, this._delegateConnectIPAddresses);
  559. }
  560. public string Connect(string host, string username, string password)
  561. {
  562. return this.Connect(host, 110, username, password);
  563. }
  564. public IAsyncResult BeginConnect(string host, string username, string password, AsyncCallback callback)
  565. {
  566. return this.BeginConnect(host, 110, username, password, callback);
  567. }
  568. public string Connect(string host, int port, string username, string password)
  569. {
  570. this.OnConnecting();
  571. base.Connect(host, port);
  572. string response = this.ReadLine();
  573. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  574. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password, host));
  575. response = this.Command("USER " + username);
  576. string presponse = this.Command("PASS " + password);
  577. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, host, response));
  578. /*response = this.Command("STAT");
  579. this._messageCount = System.Convert.ToInt32(response.Split(' ')[1]);
  580. this._totalSize = System.Convert.ToInt32(response.Split(' ')[2]);*/
  581. return presponse;
  582. }
  583. public IAsyncResult BeginConnect(string host, int port, string username, string password, AsyncCallback callback)
  584. {
  585. this._delegateConnectAuth = this.Connect;
  586. return this._delegateConnectAuth.BeginInvoke(host, port, username, password, callback, this._delegateConnectAuth);
  587. }
  588. public new string EndConnect(IAsyncResult result)
  589. {
  590. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  591. }
  592. /// <summary>
  593. /// Connects the object with the remote POP server using the given parameters and APOP.
  594. /// </summary>
  595. /// <param name="user">Username on the remote POP server.</param>
  596. /// <param name="pass">Password on the remote POP server.</param>
  597. /// <param name="host">Remote POP server address.</param>
  598. /// <example>
  599. /// This will connect to the remote POP server using APOP.<br /><br />
  600. /// <code>
  601. /// C#
  602. ///
  603. /// Pop3Client pop = new Pop3Client();
  604. /// pop.APOPConnect("pop.myisp.com","username","password");
  605. ///
  606. /// VB.NET
  607. ///
  608. /// Dim pop As New Pop3Client()
  609. /// pop.APOPConnect("pop.myisp.com","username","password")
  610. ///
  611. /// JScript.NET
  612. ///
  613. /// var pop:Pop3Client = new Pop3Client();
  614. /// pop.APOPConnect("pop.myisp.com","username","password");
  615. /// </code>
  616. /// </example>
  617. public string APOPConnect(string host, string user, string pass)
  618. {
  619. return this.APOPConnect(host, 110, user, pass);
  620. }
  621. public IAsyncResult BeginAPOPConnect(string host, string user, string pass, AsyncCallback callback)
  622. {
  623. return this.BeginAPOPConnect(host, 110, user, pass, callback);
  624. }
  625. /// <summary>
  626. /// Connects the object with the remote POP server using the given parameters and APOP.
  627. /// </summary>
  628. /// <param name="user">Username on the remote POP server.</param>
  629. /// <param name="pass">Password on the remote POP server.</param>
  630. /// <param name="host">Remote POP server address.</param>
  631. /// <param name="port">Port to be used.</param>
  632. /// <example>
  633. /// This will connect to the remote POP server using APOP.<br /><br />
  634. /// <code>
  635. /// C#
  636. ///
  637. /// Pop3Client pop = new Pop3Client();
  638. /// pop.APOPConnect("pop.myisp.com","username","password",8503);
  639. ///
  640. /// VB.NET
  641. ///
  642. /// Dim pop As New Pop3Client()
  643. /// pop.APOPConnect("pop.myisp.com","username","password",8503)
  644. ///
  645. /// JScript.NET
  646. ///
  647. /// var pop:Pop3Client = new Pop3Client();
  648. /// pop.APOPConnect("pop.myisp.com","username","password",8503);
  649. /// </code>
  650. /// </example>
  651. public string APOPConnect(string host, int port, string user, string pass)
  652. {
  653. string response = this.Connect(host, port);
  654. string presponse = "";
  655. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(user, pass, host));
  656. Match timestamp = Regex.Match(response, @"<.+@.+>");
  657. if (timestamp.Success)
  658. {
  659. string encrypted = timestamp.Value + pass;
  660. presponse = this.Command("APOP " + user + " " + ActiveUp.Net.Mail.Crypto.MD5Digest(encrypted));
  661. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(user, pass, host, response));
  662. response = this.Command("STAT");
  663. this._messageCount = System.Convert.ToInt32(response.Split(' ')[1]);
  664. this._totalSize = System.Convert.ToInt32(response.Split(' ')[2]);
  665. }
  666. return presponse;
  667. }
  668. public IAsyncResult BeginAPOPConnect(string host, int port, string username, string password, AsyncCallback callback)
  669. {
  670. this._delegateConnectAPOP = this.APOPConnect;
  671. return this._delegateConnectAPOP.BeginInvoke(host, port, username, password, callback, this._delegateConnectAPOP);
  672. }
  673. public string EndAPOPConnect(IAsyncResult result)
  674. {
  675. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  676. }
  677. /// <summary>
  678. /// Gets a value indicating whether this instance is connected.
  679. /// </summary>
  680. /// <value>
  681. /// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
  682. /// </value>
  683. public override bool IsConnected
  684. {
  685. get
  686. {
  687. if (this.Client != null)
  688. return this.Client.Connected;
  689. else
  690. return false;
  691. }
  692. }
  693. #endregion
  694. #region SSL methods
  695. #if !PocketPC
  696. public string ConnectSsl(string host)
  697. {
  698. return this.ConnectSsl(host, 995, new ActiveUp.Net.Security.SslHandShake(host));
  699. }
  700. public IAsyncResult BeginConnectSsl(string host, AsyncCallback callback)
  701. {
  702. return this.BeginConnectSsl(host, 995, new ActiveUp.Net.Security.SslHandShake(host), callback);
  703. }
  704. public string ConnectSsl(string host, ActiveUp.Net.Security.SslHandShake sslHandShake)
  705. {
  706. return this.ConnectSsl(host, 995, sslHandShake);
  707. }
  708. public IAsyncResult BeginConnectSsl(string host, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  709. {
  710. return this.BeginConnectSsl(host, 995, sslHandShake, callback);
  711. }
  712. public string ConnectSsl(string host, int port)
  713. {
  714. return this.ConnectSsl(host, port, new ActiveUp.Net.Security.SslHandShake(host));
  715. }
  716. public override IAsyncResult BeginConnectSsl(string host, int port, AsyncCallback callback)
  717. {
  718. return this.BeginConnectSsl(host, port, new SslHandShake(host), callback);
  719. }
  720. public string ConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  721. {
  722. this.OnConnecting();
  723. base.Connect(host, port);
  724. this.DoSslHandShake(sslHandShake);
  725. string response = this.ReadLine();
  726. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  727. return response;
  728. }
  729. public IAsyncResult BeginConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  730. {
  731. this._delegateConnectSsl = this.ConnectSsl;
  732. return this._delegateConnectSsl.BeginInvoke(host, port, sslHandShake, callback, this._delegateConnectSsl);
  733. }
  734. public string ConnectSsl(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  735. {
  736. this.OnConnecting();
  737. base.Connect(addr, port);
  738. this.DoSslHandShake(sslHandShake);
  739. string response = this.ReadLine();
  740. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  741. return response;
  742. }
  743. public IAsyncResult BeginConnectSsl(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  744. {
  745. this._delegateConnectSslIPAddress = this.ConnectSsl;
  746. return this._delegateConnectSslIPAddress.BeginInvoke(addr, port, sslHandShake, callback, this._delegateConnectSslIPAddress);
  747. }
  748. public string ConnectSsl(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  749. {
  750. this.OnConnecting();
  751. base.Connect(addresses, port);
  752. this.DoSslHandShake(sslHandShake);
  753. string response = this.ReadLine();
  754. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  755. return response;
  756. }
  757. public IAsyncResult BeginConnectSsl(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  758. {
  759. this._delegateConnectSslIPAddresses = this.ConnectSsl;
  760. return this._delegateConnectSslIPAddresses.BeginInvoke(addresses, port, sslHandShake, callback, this._delegateConnectSslIPAddresses);
  761. }
  762. public string ConnectSsl(string host, string user, string pass)
  763. {
  764. return this.ConnectSsl(host, 995, user, pass, new SslHandShake(host));
  765. }
  766. public IAsyncResult BeginConnectSsl(string host, string user, string pass, AsyncCallback callback)
  767. {
  768. return this.BeginConnectSsl(host, 995, user, pass, new SslHandShake(host), callback);
  769. }
  770. public string ConnectSsl(string host, string user, string pass, SslHandShake sslHandShake)
  771. {
  772. return this.ConnectSsl(host, 995, user, pass, sslHandShake);
  773. }
  774. public IAsyncResult BeginConnectSsl(string host, string user, string pass, SslHandShake sslHandShake, AsyncCallback callback)
  775. {
  776. return this.BeginConnectSsl(host, 995, user, pass, sslHandShake, callback);
  777. }
  778. public string ConnectSsl(string host, int port, string user, string pass)
  779. {
  780. return this.ConnectSsl(host, port, user, pass, new SslHandShake(host));
  781. }
  782. public IAsyncResult BeginConnectSsl(string host, int port, string user, string pass, AsyncCallback callback)
  783. {
  784. return this.BeginConnectSsl(host, port, user, pass, new SslHandShake(host), callback);
  785. }
  786. public string ConnectSsl(string host, int port, string user, string pass, SslHandShake sslHandShake)
  787. {
  788. this.OnConnecting();
  789. base.Connect(host, port);
  790. this.DoSslHandShake(sslHandShake);
  791. string response = this.ReadLine();
  792. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  793. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(user, pass, host));
  794. response = this.Command("USER " + user);
  795. string presponse = this.Command("PASS " + pass);
  796. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(user, pass, host, response));
  797. /*response = this.Command("STAT");
  798. var splited = response.Split(' ');
  799. this._messageCount = System.Convert.ToInt32(splited[1]);
  800. this._totalSize = System.Convert.ToInt32(splited[2]);*/
  801. return presponse;
  802. }
  803. public IAsyncResult BeginConnectSsl(string host, int port, string user, string pass, SslHandShake sslHandShake, AsyncCallback callback)
  804. {
  805. this._delegateConnectSslAuth = this.ConnectSsl;
  806. return this._delegateConnectSslAuth.BeginInvoke(host, port, user, pass, sslHandShake, callback, this._delegateConnectSslAuth);
  807. }
  808. public override string EndConnectSsl(IAsyncResult result)
  809. {
  810. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  811. }
  812. #endif
  813. #endregion
  814. #region SASL authentication
  815. /// <summary>
  816. /// Authenticates using the given SASL mechanism.
  817. /// </summary>
  818. /// <param name="username">Username to authenticate as.</param>
  819. /// <param name="password">Password.</param>
  820. /// <param name="mechanism">SASL mechanism to be used.</param>
  821. /// <returns>The server's response.</returns>
  822. /// <example>
  823. /// <code>
  824. /// C#
  825. ///
  826. /// Pop3Client pop = new Pop3Client();
  827. /// pop.Connect("mail.myhost.com");
  828. /// pop.Authenticate("user","pass",SASLMechanism.CramMd5);
  829. /// pop.Disconnect();
  830. ///
  831. /// VB.NET
  832. ///
  833. /// Dim pop As New Pop3Client
  834. /// pop.Connect("mail.myhost.com")
  835. /// pop.Authenticate("user","pass",SASLMechanism.CramMd5)
  836. /// pop.Disconnect()
  837. ///
  838. /// JScript.NET
  839. ///
  840. /// var pop:Pop3Client = new Pop3Client();
  841. /// pop.Connect("mail.myhost.com");
  842. /// pop.Authenticate("user","pass",SASLMechanism.CramMd5);
  843. /// pop.Disconnect();
  844. /// </code>
  845. /// </example>
  846. public string Authenticate(string username, string password, SaslMechanism mechanism)
  847. {
  848. switch (mechanism)
  849. {
  850. case ActiveUp.Net.Mail.SaslMechanism.CramMd5:
  851. return this._CramMd5(username, password);
  852. case ActiveUp.Net.Mail.SaslMechanism.Login:
  853. return this._Login(username, password);
  854. }
  855. return string.Empty;
  856. }
  857. public override IAsyncResult BeginAuthenticate(string username, string password, SaslMechanism mechanism, AsyncCallback callback)
  858. {
  859. this._delegateAuthenticate = this.Authenticate;
  860. return this._delegateAuthenticate.BeginInvoke(username, password, mechanism, callback, null);
  861. }
  862. public string EndAuthenticate(IAsyncResult result)
  863. {
  864. return this._delegateAuthenticate.EndInvoke(result);
  865. }
  866. #endregion
  867. #region Disconnect method
  868. /// <summary>
  869. /// Disconnects the client from the remote server.
  870. /// </summary>
  871. /// <example>
  872. /// <code>
  873. /// C#
  874. ///
  875. /// Pop3Client pop = new Pop3Client();
  876. /// pop.Connect("mail.myhost.com","user","pass");
  877. /// //Do some work...
  878. /// pop.Disconnect();
  879. ///
  880. /// VB.NET
  881. ///
  882. /// Dim pop As New Pop3Client
  883. /// pop.Connect("mail.myhost.com","user","pass")
  884. /// 'Do some work...
  885. /// pop.Disconnect()
  886. ///
  887. /// JScript.NET
  888. ///
  889. /// var pop:Pop3Client = new Pop3Client();
  890. /// pop.Connect("mail.myhost.com","user","pass");
  891. /// //Do some work...
  892. /// pop.Disconnect();
  893. /// </code>
  894. /// </example>
  895. public override string Disconnect()
  896. {
  897. this.OnDisconnecting();
  898. string response = this.Command("QUIT");
  899. this.Close();
  900. this.OnDisconnected(new ActiveUp.Net.Mail.DisconnectedEventArgs(response));
  901. return response;
  902. }
  903. public IAsyncResult BeginDisconnect(AsyncCallback callback)
  904. {
  905. this._delegateDisconnect = this.Disconnect;
  906. return this._delegateDisconnect.BeginInvoke(callback, null);
  907. }
  908. public string EndDisconnect(IAsyncResult result)
  909. {
  910. return this._delegateDisconnect.EndInvoke(result);
  911. }
  912. #endregion
  913. #endregion
  914. #region Command sending and receiving, stream access
  915. /// <summary>
  916. /// Sends the provided string to the server.
  917. /// </summary>
  918. /// <param name="command">The string to be sent to the server.</param>
  919. /// <returns>The server's response.</returns>
  920. /// <remarks>This method is to be used only with commands that return single-line responses.</remarks>
  921. /// <example>
  922. /// <code>
  923. /// C#
  924. ///
  925. /// Pop3Client pop = new Pop3Client();
  926. /// pop.Connect("mail.myhost.com","user","pass");
  927. /// string response = pop.Command("XANYCOMMAND anyarguments");
  928. /// pop.Disconnect();
  929. ///
  930. /// VB.NET
  931. ///
  932. /// Dim pop As New Pop3Client
  933. /// pop.Connect("mail.myhost.com","user","pass")
  934. /// Dim response As String = pop.Command("XANYCOMMAND anyarguments")
  935. /// pop.Disconnect()
  936. ///
  937. /// JScript.NET
  938. ///
  939. /// var pop:Pop3Client = new Pop3Client();
  940. /// pop.Connect("mail.myhost.com","user","pass");
  941. /// var response:string = pop.Command("XANYCOMMAND anyarguments");
  942. /// pop.Disconnect();
  943. /// </code>
  944. /// </example>
  945. public string Command(string command)
  946. {
  947. this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs(command));
  948. //this.GetStream().Write(System.Text.Encoding.ASCII.GetBytes(command + "\r\n"), 0, command.Length + 2);
  949. #if !PocketPC
  950. this.GetStream().Write(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(command + "\r\n"), 0, command.Length + 2);
  951. #else
  952. this.GetStream().Write(PPCEncode.GetBytes(command + "\r\n"), 0, command.Length + 2);
  953. #endif
  954. #if !PocketPC
  955. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
  956. #else
  957. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), PPCEncode);
  958. #endif
  959. string response = sr.ReadLine();
  960. this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs(command));
  961. this.OnTcpReading();
  962. if (response == null || !response.StartsWith("+"))
  963. throw new ActiveUp.Net.Mail.Pop3Exception(command.StartsWith("PASS") ? "PASS *****" : command, response);
  964. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs(response));
  965. return response;
  966. }
  967. public IAsyncResult BeginCommand(string command, AsyncCallback callback)
  968. {
  969. this._delegateCommand = this.Command;
  970. return this._delegateCommand.BeginInvoke(command, callback, null);
  971. }
  972. public string EndCommand(IAsyncResult result)
  973. {
  974. return this._delegateCommand.EndInvoke(result);
  975. }
  976. /// <summary>
  977. /// Sends the provided string to the server.
  978. /// </summary>
  979. /// <param name="command">The string to be sent to the server.</param>
  980. /// <returns>The server's response.</returns>
  981. /// <remarks>This method is to be used only with commands that return multi-line responses.</remarks>
  982. /// <example>
  983. /// <code>
  984. /// C#
  985. ///
  986. /// Pop3Client pop = new Pop3Client();
  987. /// pop.Connect("mail.myhost.com","user","pass");
  988. /// string response = pop.CommandMultiline("XANYCOMMAND anyarguments");
  989. /// pop.Disconnect();
  990. ///
  991. /// VB.NET
  992. ///
  993. /// Dim pop As New Pop3Client
  994. /// pop.Connect("mail.myhost.com","user","pass")
  995. /// Dim response As String = pop.CommandMultiline("XANYCOMMAND anyarguments")
  996. /// pop.Disconnect()
  997. ///
  998. /// JScript.NET
  999. ///
  1000. /// var pop:Pop3Client = new Pop3Client();
  1001. /// pop.Connect("mail.myhost.com","user","pass");
  1002. /// var response:string = pop.CommandMultiline("XANYCOMMAND anyarguments");
  1003. /// pop.Disconnect();
  1004. /// </code>
  1005. /// </example>
  1006. public string CommandMultiline(string command)
  1007. {
  1008. this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs(command));
  1009. #if !PocketPC
  1010. this.GetStream().Write(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(command + "\r\n"), 0, command.Length + 2);
  1011. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
  1012. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  1013. this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs(command));
  1014. #else
  1015. this.GetStream().Write(PPCEncode.GetBytes(command + "\r\n"), 0, command.Length + 2);
  1016. this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs(command));
  1017. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  1018. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), PPCEncode);
  1019. #endif
  1020. string str = "";
  1021. this.OnTcpReading();
  1022. str = sr.ReadLine();
  1023. if (!str.StartsWith("+")) throw new Pop3Exception(command, str);
  1024. while (true)
  1025. {
  1026. str = sr.ReadLine();
  1027. if (str != ".") sb.Append(str + "\r\n");
  1028. else break;
  1029. }
  1030. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs("Read multiline command response."));
  1031. return sb.ToString().Replace("\r\n..\r\n", "\r\n.\r\n");
  1032. }
  1033. public IAsyncResult BeginCommandMultiline(string command, AsyncCallback callback)
  1034. {
  1035. this._delegateCommand = this.CommandMultiline;
  1036. return this._delegateCommand.BeginInvoke(command, callback, null);
  1037. }
  1038. public string EndCommandMultiline(IAsyncResult result)
  1039. {
  1040. return this._delegateCommand.EndInvoke(result);
  1041. }
  1042. /// <summary>
  1043. /// Gets the communacation stream of this object.
  1044. /// </summary>
  1045. /// <returns>A Stream object, either of type NetworkStream or SslStream if the channel is secured.</returns>
  1046. // public new System.IO.Stream GetStream()
  1047. // {
  1048. //#if !PocketPC
  1049. // if (this._sslStream != null) return this._sslStream;
  1050. //#endif
  1051. // return base.GetStream();
  1052. // }
  1053. #endregion
  1054. #region Mailbox management
  1055. /// <summary>
  1056. /// Marks the message with the given index for deletion on the remote POP server.
  1057. /// </summary>
  1058. /// <param name="indexOnServer">Index of the message to mark for deletion.</param>
  1059. /// <remarks>
  1060. /// This action can be cancelled by using the Reset() method before disconnection.
  1061. /// <see cref="Reset"/>
  1062. /// </remarks>
  1063. /// <example>
  1064. /// <code>
  1065. /// C#
  1066. ///
  1067. /// Pop3Client pop = new Pop3Client();
  1068. /// pop.Connect("pop.myisp.com","username","password");
  1069. /// pop.DeleteMessage(1);
  1070. /// pop.Disconnect();
  1071. /// //Message 1 deleted.
  1072. ///
  1073. /// VB.NET
  1074. ///
  1075. /// Dim pop As New Pop3Client()
  1076. /// pop.Connect("pop.myisp.com","username","password")
  1077. /// pop.DeleteMessage(1)
  1078. /// pop.Disconnect()
  1079. /// 'Message 1 deleted.
  1080. ///
  1081. /// JScript.NET
  1082. ///
  1083. /// var pop:Pop3Client = new Pop3Client();
  1084. /// pop.Connect("pop.myisp.com","username","password");
  1085. /// pop.DeleteMessage(1);
  1086. /// pop.Disconnect();
  1087. /// //Message 1 deleted.
  1088. /// </code>
  1089. /// </example>
  1090. public void DeleteMessage(int indexOnServer)
  1091. {
  1092. string response = this.Command("DELE " + indexOnServer.ToString());
  1093. if (!response.StartsWith("+OK")) throw new ActiveUp.Net.Mail.Pop3Exception("DELE failed : " + response);
  1094. }
  1095. public IAsyncResult BeginDeleteMessage(int indexOnServer, AsyncCallback callback)
  1096. {
  1097. this._delegateDeleteMessage = this.DeleteMessage;
  1098. return this._delegateDeleteMessage.BeginInvoke(indexOnServer, callback, null);
  1099. }
  1100. public void EndDeleteMessage(IAsyncResult result)
  1101. {
  1102. this._delegateDeleteMessage.EndInvoke(result);
  1103. }
  1104. /// <summary>
  1105. /// Unmarks all messages that were marked for deletion.
  1106. /// </summary>
  1107. /// <returns>The amount of messages unmarked.</returns>
  1108. /// <example>
  1109. /// <code>
  1110. /// C#
  1111. ///
  1112. /// ActiveUp.Net.Mail.Pop3Client pop = new ActiveUp.Net.Mail.Pop3Client();
  1113. /// pop.Connect("pop.myisp.com","username","password");
  1114. /// pop.DeleteMessage(1);
  1115. /// //Message is marked for deletion.
  1116. /// pop.Reset();
  1117. /// //Message won't be deleted.
  1118. /// pop.Disconnect();
  1119. /// //Nothing happened.
  1120. ///
  1121. /// VB.NET
  1122. ///
  1123. /// Dim pop As New ActiveUp.Net.Mail.Pop3Client()
  1124. /// pop.Connect("pop.myisp.com","username","password")
  1125. /// pop.DeleteMessage(1)
  1126. /// 'Message is marked for deletion.
  1127. /// pop.Reset()
  1128. /// 'Message won't be deleted.
  1129. /// pop.Disconnect()
  1130. /// 'Nothing happened.
  1131. ///
  1132. /// JScript.NET
  1133. ///
  1134. /// var pop:ActiveUp.Net.Mail.Pop3Client = new ActiveUp.Net.Mail.Pop3Client();
  1135. /// pop.Connect("pop.myisp.com","username","password");
  1136. /// pop.DeleteMessage(1);
  1137. /// //Message is marked for deletion.
  1138. /// pop.Reset();
  1139. /// //Message won't be deleted.
  1140. /// pop.Disconnect();
  1141. /// //Nothing happened.
  1142. /// </code>
  1143. /// </example>
  1144. public int Reset()
  1145. {
  1146. string response = this.Command("RSET");
  1147. if (!response.StartsWith("+OK")) throw new ActiveUp.Net.Mail.Pop3Exception("RSET failed : " + response);
  1148. else return System.Convert.ToInt32(response.Split(' ')[1]);
  1149. }
  1150. public IAsyncResult BeginReset(AsyncCallback callback)
  1151. {
  1152. this._delegateReset = this.Reset;
  1153. return this._delegateReset.BeginInvoke(callback, null);
  1154. }
  1155. public int EndReset(IAsyncResult result)
  1156. {
  1157. return this._delegateReset.EndInvoke(result);
  1158. }
  1159. #endregion
  1160. #region Message retrieval methods
  1161. #region Message as raw data
  1162. public byte[] RetrieveMessage(int messageIndex)
  1163. {
  1164. var msg = RetrieveMessageString(messageIndex);
  1165. #if !PocketPC
  1166. byte[] buf = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(msg);
  1167. #else
  1168. byte[] buf = PPCEncode.GetBytes(sb.ToString());
  1169. #endif
  1170. this.OnMessageRetrieved(new ActiveUp.Net.Mail.MessageRetrievedEventArgs(buf, messageIndex, this.MessageCount));
  1171. return buf;
  1172. }
  1173. /// <summary>
  1174. /// Retrieves the message at the given index.
  1175. /// </summary>
  1176. /// <param name="messageIndex">The index of the message to be retrieved.</param>
  1177. /// <returns>A byte array containing the message data.</returns>
  1178. /// <example>
  1179. /// <code>
  1180. /// C#
  1181. ///
  1182. /// Pop3Client pop = new Pop3Client();
  1183. /// pop.Connect("mail.myhost.com","user","pass");
  1184. /// byte[] messageData = pop.RetrieveMessage(1);
  1185. /// pop.Disconnect();
  1186. ///
  1187. /// VB.NET
  1188. ///
  1189. /// Dim pop As New Pop3Client
  1190. /// pop.Connect("mail.myhost.com","user","pass")
  1191. /// Dim messageData as Byte() = pop.RetrieveMessage(1)
  1192. /// pop.Disconnect()
  1193. ///
  1194. /// JScript.NET
  1195. ///
  1196. /// var pop:Pop3Client = new Pop3Client();
  1197. /// pop.Connect("mail.myhost.com","user","pass");
  1198. /// var messageData:byte[] = pop.RetrieveMessage(1);
  1199. /// pop.Disconnect();
  1200. /// </code>
  1201. /// </example>
  1202. public string RetrieveMessageString(int messageIndex)
  1203. {
  1204. if (messageIndex > 0)
  1205. {
  1206. this.OnMessageRetrieving(new ActiveUp.Net.Mail.MessageRetrievingEventArgs(messageIndex, this.MessageCount));
  1207. this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs("RETR " + messageIndex.ToString()));
  1208. #if !PocketPC
  1209. this.GetStream().Write(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes("RETR " + messageIndex.ToString() + "\r\n"), 0, 7 + messageIndex.ToString().Length);
  1210. this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs("RETR " + messageIndex.ToString()));
  1211. this.OnTcpReading();
  1212. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
  1213. #else
  1214. this.GetStream().Write(PPCEncode.GetBytes("RETR " + messageIndex.ToString() + "\r\n"), 0, 7 + messageIndex.ToString().Length);
  1215. this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs("RETR " + messageIndex.ToString()));
  1216. this.OnTcpReading();
  1217. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), PPCEncode));
  1218. #endif
  1219. System.Text.StringBuilder sb;
  1220. try
  1221. {
  1222. sb = new System.Text.StringBuilder(30720000); // 30 mb for buffer
  1223. }
  1224. catch (OutOfMemoryException)
  1225. {
  1226. // No more free physical memory, let's use virtual memory
  1227. sb = new System.Text.StringBuilder();
  1228. }
  1229. var str = sr.ReadLine();
  1230. if (str.StartsWith("+OK"))
  1231. {
  1232. while (true)
  1233. {
  1234. str = sr.ReadLine();
  1235. if (str != ".")
  1236. {
  1237. if (!str.StartsWith(".."))
  1238. sb.Append(str + "\r\n");
  1239. else
  1240. {
  1241. if (!str.StartsWith("..."))
  1242. sb.Append(str.Remove(0, 1) + "\r\n");
  1243. else
  1244. sb.Append(str + "\r\n");
  1245. }
  1246. }
  1247. else break;
  1248. }
  1249. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs("Long message data..."));
  1250. }
  1251. else throw new ActiveUp.Net.Mail.Pop3Exception("RETR", str);
  1252. sr = null;
  1253. return sb.ToString();
  1254. }
  1255. else
  1256. throw new Pop3Exception("The specified message index is invalid. Please specify an index that is greater than 0.");
  1257. }
  1258. public IAsyncResult BeginRetrieveMessage(int messageIndex, AsyncCallback callback)
  1259. {
  1260. return this.BeginRetrieveMessage(messageIndex, false, callback);
  1261. }
  1262. /// <summary>
  1263. /// Retrieves the message at the given index.
  1264. /// </summary>
  1265. /// <param name="messageIndex">The index of the message to be retrieved.</param>
  1266. /// <param name="deleteMessage">If true, the message will be deleted after it has been retrieved.</param>
  1267. /// <returns>A byte array containing the message data.</returns>
  1268. /// <example>
  1269. /// <code>
  1270. /// C#
  1271. ///
  1272. /// Pop3Client pop = new Pop3Client();
  1273. /// pop.Connect("mail.myhost.com","user","pass");
  1274. /// byte[] messageData = pop.RetrieveMessage(1,true);
  1275. /// pop.Disconnect();
  1276. /// //Message 1 is deleted.
  1277. ///
  1278. /// VB.NET
  1279. ///
  1280. /// Dim pop As New Pop3Client
  1281. /// pop.Connect("mail.myhost.com","user","pass")
  1282. /// Dim messageData as Byte() = pop.RetrieveMessage(1,True)
  1283. /// pop.Disconnect()
  1284. /// 'Message 1 is deleted.
  1285. ///
  1286. /// JScript.NET
  1287. ///
  1288. /// var pop:Pop3Client = new Pop3Client();
  1289. /// pop.Connect("mail.myhost.com","user","pass");
  1290. /// var messageData:byte[] = pop.RetrieveMessage(1,true);
  1291. /// pop.Disconnect();
  1292. /// //Message 1 is deleted.
  1293. /// </code>
  1294. /// </example>
  1295. public byte[] RetrieveMessage(int messageIndex, bool deleteMessage)
  1296. {
  1297. byte[] buffer = this.RetrieveMessage(messageIndex);
  1298. if (deleteMessage) this.DeleteMessage(messageIndex);
  1299. return buffer;
  1300. }
  1301. public IAsyncResult BeginRetrieveMessage(int messageIndex, bool deleteMessage, AsyncCallback callback)
  1302. {
  1303. this._delegateRetrieveMessage = this.RetrieveMessage;
  1304. return this._delegateRetrieveMessage.BeginInvoke(messageIndex, deleteMessage, callback, null);
  1305. }
  1306. public byte[] EndRetrieveMessage(IAsyncResult result)
  1307. {
  1308. return this._delegateRetrieveMessage.EndInvoke(result);
  1309. }
  1310. #endregion
  1311. #region Message as object
  1312. /// <summary>
  1313. /// Retrieves the message at the given index.
  1314. /// </summary>
  1315. /// <param name="message_index">The index of the message to be retrieved.</param>
  1316. /// <returns>A Message object representing the message.</returns>
  1317. /// <example>
  1318. /// <code>
  1319. /// C#
  1320. ///
  1321. /// Pop3Client pop = new Pop3Client();
  1322. /// pop.Connect("mail.myhost.com","user","pass");
  1323. /// Message message = pop.RetrieveMessageObject(1);
  1324. /// pop.Disconnect();
  1325. ///
  1326. /// VB.NET
  1327. ///
  1328. /// Dim pop As New Pop3Client
  1329. /// pop.Connect("mail.myhost.com","user","pass")
  1330. /// Dim message as Message = pop.RetrieveMessageObject(1)
  1331. /// pop.Disconnect()
  1332. ///
  1333. /// JScript.NET
  1334. ///
  1335. /// var pop:Pop3Client = new Pop3Client();
  1336. /// pop.Connect("mail.myhost.com","user","pass");
  1337. /// var message:Message = pop.RetrieveMessageObject(1);
  1338. /// pop.Disconnect();
  1339. /// </code>
  1340. /// </example>
  1341. public Message RetrieveMessageObject(int message_index)
  1342. {
  1343. var msg = RetrieveMessageString(message_index);
  1344. var message = Parser.ParseMessage(ref msg);
  1345. return message;
  1346. }
  1347. public IAsyncResult BeginRetrieveMessageObject(int messageIndex, AsyncCallback callback)
  1348. {
  1349. return this.BeginRetrieveMessageObject(messageIndex, false, callback);
  1350. }
  1351. /// <summary>
  1352. /// Retrieves the message at the given index.
  1353. /// </summary>
  1354. /// <param name="message_index">The index of the message to be retrieved.</param>
  1355. /// <param name="deleteMessage">If true, the message will be deleted after it has been retrieved.</param>
  1356. /// <returns>A Message object representing the message.</returns>
  1357. /// <example>
  1358. /// <code>
  1359. /// C#
  1360. ///
  1361. /// Pop3Client pop = new Pop3Client();
  1362. /// pop.Connect("mail.myhost.com","user","pass");
  1363. /// Message message = pop.RetrieveMessageObject(1);
  1364. /// pop.Disconnect();
  1365. /// //Message 1 is deleted.
  1366. ///
  1367. /// VB.NET
  1368. ///
  1369. /// Dim pop As New Pop3Client
  1370. /// pop.Connect("mail.myhost.com","user","pass")
  1371. /// Dim message as Message = pop.RetrieveMessageObject(1)
  1372. /// pop.Disconnect()
  1373. /// 'Message 1 is deleted.
  1374. ///
  1375. /// JScript.NET
  1376. ///
  1377. /// var pop:Pop3Client = new Pop3Client();
  1378. /// pop.Connect("mail.myhost.com","user","pass");
  1379. /// var message:Message = pop.RetrieveMessageObject(1);
  1380. /// pop.Disconnect();
  1381. /// //Message 1 is deleted.
  1382. /// </code>
  1383. /// </example>
  1384. public ActiveUp.Net.Mail.Message RetrieveMessageObject(int message_index, bool deleteMessage)
  1385. {
  1386. return ActiveUp.Net.Mail.Parser.ParseMessage(this.RetrieveMessage(message_index, deleteMessage));
  1387. }
  1388. public IAsyncResult BeginRetrieveMessageObject(int messageIndex, bool deleteMessage, AsyncCallback callback)
  1389. {
  1390. this._delegateRetrieveMessageObject = this.RetrieveMessageObject;
  1391. return this._delegateRetrieveMessageObject.BeginInvoke(messageIndex, deleteMessage, callback, null);
  1392. }
  1393. public Message EndRetrieveMessageObject(IAsyncResult result)
  1394. {
  1395. return this._delegateRetrieveMessageObject.EndInvoke(result);
  1396. }
  1397. #endregion
  1398. #region Store message data to a file
  1399. /// <summary>
  1400. /// Retrieves and stores the message at the specified index to the specified path.
  1401. /// Deletes the message once retrieval operation is complete.
  1402. /// </summary>
  1403. /// <param name="messageIndex">Index of the message to be retrieved.</param>
  1404. /// <param name="deleteMessage">If true, the message will be deleted after it has been retrieved.</param>
  1405. /// <param name="destinationPath">The path where the message has to be stored.</param>
  1406. /// <example>
  1407. /// <code>
  1408. /// C#
  1409. ///
  1410. /// Pop3Client pop = new Pop3Client();
  1411. /// pop.Connect("mail.myhost.com","user","pass");
  1412. /// pop.StoreMessage(1,"C:\\My headers\\myheader.eml");
  1413. /// pop.Disconnect();
  1414. ///
  1415. /// VB.NET
  1416. ///
  1417. /// Dim pop As New Pop3Client
  1418. /// pop.Connect("mail.myhost.com","user","pass")
  1419. /// pop.StoreMessage(1,"C:\My headers\myheader.eml")
  1420. /// pop.Disconnect()
  1421. ///
  1422. /// JScript.NET
  1423. ///
  1424. /// var pop:Pop3Client = new Pop3Client();
  1425. /// pop.Connect("mail.myhost.com","user","pass");
  1426. /// pop.StoreMessage(1,"C:\\My headers\\myheader.eml");
  1427. /// pop.Disconnect();
  1428. /// </code>
  1429. /// </example>
  1430. public void StoreMessage(int messageIndex, bool deleteMessage, string destinationPath)
  1431. {
  1432. this.StoreToFile(destinationPath, this.RetrieveMessage(messageIndex, deleteMessage));
  1433. }
  1434. public IAsyncResult BeginStoreMessage(int messageIndex, bool deleteMessage, string destinationPath, AsyncCallback callback)
  1435. {
  1436. this._delegateStoreMessage = this.StoreMessage;
  1437. return this._delegateStoreMessage.BeginInvoke(messageIndex, deleteMessage, destinationPath, callback, null);
  1438. }
  1439. public void EndStoreMessage(IAsyncResult result)
  1440. {
  1441. this._delegateStoreMessage.EndInvoke(result);
  1442. }
  1443. #endregion
  1444. #endregion
  1445. #region Header retrieval methods
  1446. #region Header as raw data
  1447. public byte[] RetrieveHeader(int messageIndex)
  1448. {
  1449. return this.RetrieveHeader(messageIndex, 0);
  1450. }
  1451. public IAsyncResult BeginRetrieveHeader(int messageIndex, AsyncCallback callback)
  1452. {
  1453. return this.BeginRetrieveHeader(messageIndex, 0, callback);
  1454. }
  1455. /// <summary>
  1456. /// Retrieves the Header of the message at the given index, plus a given number of lines beyond the Header limit.
  1457. /// </summary>
  1458. /// <param name="messageIndex">Index of the Header to be retrieved.</param>
  1459. /// <param name="numberOfBodyLines">Number of lines to retrieve after the Header separation.</param>
  1460. /// <returns>A byte array containing the Header data.</returns>
  1461. /// <example>
  1462. /// <code>
  1463. /// C#
  1464. ///
  1465. /// Pop3Client pop = new Pop3Client();
  1466. /// pop.Connect("mail.myhost.com","user","pass");
  1467. /// byte[] headerData = pop.RetrieveHeader(1,10);
  1468. /// pop.Disconnect();
  1469. ///
  1470. /// VB.NET
  1471. ///
  1472. /// Dim pop As New Pop3Client
  1473. /// pop.Connect("mail.myhost.com","user","pass")
  1474. /// Dim headerData as Byte() = pop.RetrieveHeader(1,10)
  1475. /// pop.Disconnect()
  1476. ///
  1477. /// JScript.NET
  1478. ///
  1479. /// var pop:Pop3Client = new Pop3Client();
  1480. /// pop.Connect("mail.myhost.com","user","pass");
  1481. /// var headerData:byte[] = pop.RetrieveHeader(1,10);
  1482. /// pop.Disconnect();
  1483. /// </code>
  1484. /// </example>
  1485. public byte[] RetrieveHeader(int messageIndex, int numberOfBodyLines)
  1486. {
  1487. this.OnHeaderRetrieving(new ActiveUp.Net.Mail.HeaderRetrievingEventArgs(messageIndex, this.MessageCount));
  1488. string header = this.CommandMultiline("TOP " + messageIndex.ToString() + " " + numberOfBodyLines.ToString());
  1489. //header = header.Replace(header.Split('\n')[0],"").TrimStart('\n');
  1490. //byte[] buf = System.Text.Encoding.ASCII.GetBytes(header);
  1491. #if !PocketPC
  1492. byte[] buf = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(header);
  1493. #else
  1494. byte[] buf = PPCEncode.GetBytes(header);
  1495. #endif
  1496. this.OnHeaderRetrieved(new ActiveUp.Net.Mail.HeaderRetrievedEventArgs(buf, messageIndex, this.MessageCount));
  1497. return buf;
  1498. }
  1499. public IAsyncResult BeginRetrieveHeader(int messageIndex, int numberOfBodyLines, AsyncCallback callback)
  1500. {
  1501. this._delegateRetrieveHeader = this.RetrieveHeader;
  1502. return this._delegateRetrieveHeader.BeginInvoke(messageIndex, numberOfBodyLines, callback, null);
  1503. }
  1504. public byte[] EndRetrieveHeader(IAsyncResult result)
  1505. {
  1506. return this._delegateRetrieveHeader.EndInvoke(result);
  1507. }
  1508. #endregion
  1509. #region Header as object
  1510. /// <summary>
  1511. /// Retrieves the Header of the message at the given index.
  1512. /// </summary>
  1513. /// <param name="messageIndex">Index of the Header to be retrieved.</param>
  1514. /// <returns>A Header object representing the header.</returns>
  1515. /// <example>
  1516. /// <code>
  1517. /// C#
  1518. ///
  1519. /// Pop3Client pop = new Pop3Client();
  1520. /// pop.Connect("mail.myhost.com","user","pass");
  1521. /// Header headerData = pop.RetrieveHeaderObject(1);
  1522. /// pop.Disconnect();
  1523. ///
  1524. /// VB.NET
  1525. ///
  1526. /// Dim pop As New Pop3Client
  1527. /// pop.Connect("mail.myhost.com","user","pass")
  1528. /// Dim headerData as Header = pop.RetrieveHeaderObject(1)
  1529. /// pop.Disconnect()
  1530. ///
  1531. /// JScript.NET
  1532. ///
  1533. /// var pop:Pop3Client = new Pop3Client();
  1534. /// pop.Connect("mail.myhost.com","user","pass");
  1535. /// var headerData:Header = pop.RetrieveHeaderObject(1);
  1536. /// pop.Disconnect();
  1537. /// </code>
  1538. /// </example>
  1539. public ActiveUp.Net.Mail.Header RetrieveHeaderObject(int messageIndex)
  1540. {
  1541. return ActiveUp.Net.Mail.Parser.ParseHeader(this.RetrieveHeader(messageIndex));
  1542. }
  1543. public IAsyncResult BeginRetrieveHeaderObject(int messageIndex, AsyncCallback callback)
  1544. {
  1545. this._delegateRetrieveHeaderObject = this.RetrieveHeaderObject;
  1546. return this._delegateRetrieveHeaderObject.BeginInvoke(messageIndex, callback, null);
  1547. }
  1548. public Header EndRetrieveHeaderObject(IAsyncResult result)
  1549. {
  1550. return this._delegateRetrieveHeaderObject.EndInvoke(result);
  1551. }
  1552. #endregion
  1553. #region Store header data to a file
  1554. /// <summary>
  1555. /// Retrieves and stores the message Header at the specified index to the specified path.
  1556. /// </summary>
  1557. /// <param name="messageIndex">Index of the message Header to be retrieved.</param>
  1558. /// <param name="destinationPath">The path where the Header has to be stored.</param>
  1559. /// <example>
  1560. /// <code>
  1561. /// C#
  1562. ///
  1563. /// Pop3Client pop = new Pop3Client();
  1564. /// pop.Connect("mail.myhost.com","user","pass");
  1565. /// pop.StoreHeader(1,"C:\\My headers\\myheader.eml");
  1566. /// pop.Disconnect();
  1567. ///
  1568. /// VB.NET
  1569. ///
  1570. /// Dim pop As New Pop3Client
  1571. /// pop.Connect("mail.myhost.com","user","pass")
  1572. /// pop.StoreHeader(1,"C:\My headers\myheader.eml")
  1573. /// pop.Disconnect()
  1574. ///
  1575. /// JScript.NET
  1576. ///
  1577. /// var pop:Pop3Client = new Pop3Client();
  1578. /// pop.Connect("mail.myhost.com","user","pass");
  1579. /// pop.StoreHeader(1,"C:\\My headers\\myheader.eml");
  1580. /// pop.Disconnect();
  1581. /// </code>
  1582. /// </example>
  1583. public void StoreHeader(int messageIndex, string destinationPath)
  1584. {
  1585. this.StoreToFile(destinationPath, this.RetrieveHeader(messageIndex));
  1586. }
  1587. public IAsyncResult BeginStoreHeader(int messageIndex, string destinationPath, AsyncCallback callback)
  1588. {
  1589. this._delegateStoreHeader = this.StoreHeader;
  1590. return this._delegateStoreHeader.BeginInvoke(messageIndex, destinationPath, callback, null);
  1591. }
  1592. public void StoreHeader(int messageIndex, int numberOfBodyLines, string destinationPath)
  1593. {
  1594. this.StoreToFile(destinationPath, this.RetrieveHeader(messageIndex, numberOfBodyLines));
  1595. }
  1596. public IAsyncResult BeginStoreHeader(int messageIndex, int numberOfBodyLines, string destinationPath, AsyncCallback callback)
  1597. {
  1598. this._delegateStoreHeader = this.StoreHeader;
  1599. return this._delegateStoreHeader.BeginInvoke(messageIndex, destinationPath, callback, null);
  1600. }
  1601. public void EndStoreHeader(IAsyncResult result)
  1602. {
  1603. this._delegateStoreHeader.EndInvoke(result);
  1604. }
  1605. #endregion
  1606. #endregion
  1607. #region Utility commands
  1608. /// <summary>
  1609. /// Issues a UIDL command and retrieves the message's unique Id (assigned by the server).
  1610. /// </summary>
  1611. /// <param name="messageIndex">The message's index.</param>
  1612. /// <returns>The message's unique Id.</returns>
  1613. /// <example>
  1614. /// <code>
  1615. /// C#
  1616. ///
  1617. /// Pop3Client pop = new Pop3Client();
  1618. /// pop.Connect("mail.myhost.com","user","pass");
  1619. /// string uniqueId = pop.UniqueId(1);
  1620. /// pop.Disconnect();
  1621. ///
  1622. /// VB.NET
  1623. ///
  1624. /// Dim pop As New Pop3Client
  1625. /// pop.Connect("mail.myhost.com","user","pass")
  1626. /// Dim uniqueId As String = pop.UniqueId(1)
  1627. /// pop.Disconnect()
  1628. ///
  1629. /// JScript.NET
  1630. ///
  1631. /// var pop:Pop3Client = new Pop3Client();
  1632. /// pop.Connect("mail.myhost.com","user","pass");
  1633. /// uniqueId:string = pop.UniqueId(1);
  1634. /// pop.Disconnect();
  1635. /// </code>
  1636. /// </example>
  1637. public string GetUniqueId(int messageIndex)
  1638. {
  1639. string resp = this.Command("UIDL " + messageIndex.ToString());
  1640. return resp.Split(' ')[2];
  1641. }
  1642. public IAsyncResult BeginGetUniqueId(int messageIndex, AsyncCallback callback)
  1643. {
  1644. this._delegateGetUniqueID = this.GetUniqueId;
  1645. return this._delegateGetUniqueID.BeginInvoke(messageIndex, callback, null);
  1646. }
  1647. public string EndGetUniqueId(IAsyncResult result)
  1648. {
  1649. return this._delegateGetUniqueID.EndInvoke(result);
  1650. }
  1651. /// <summary>
  1652. /// Issues a UIDL command and retrieves all message unique Ids (assigned by the server).
  1653. /// </summary>
  1654. /// <returns>A list of a structure containing the unique Id of the messages and their index.</returns>
  1655. /// <example>
  1656. /// <code>
  1657. /// C#
  1658. ///
  1659. /// Pop3Client pop = new Pop3Client();
  1660. /// pop.Connect("mail.myhost.com","user","pass");
  1661. /// System.Collections.Generic.List<PopServerUniqueId> uids = pop.UniqueIds();
  1662. /// pop.Disconnect();
  1663. ///
  1664. /// VB.NET
  1665. ///
  1666. /// Dim pop As New Pop3Client
  1667. /// pop.Connect("mail.myhost.com","user","pass")
  1668. /// Dim uniqueId As System.Collections.Generic.List(Of PopServerUniqueId) = pop.UniqueIds()
  1669. /// pop.Disconnect()
  1670. ///
  1671. /// JScript.NET
  1672. ///
  1673. /// var pop:Pop3Client = new Pop3Client();
  1674. /// pop.Connect("mail.myhost.com","user","pass");
  1675. /// uniqueId:System.Collections.Generic.List<PopServerUniqueId> = pop.UniqueIds();
  1676. /// pop.Disconnect();
  1677. /// </code>
  1678. /// </example>
  1679. public System.Collections.Generic.List<PopServerUniqueId> GetUniqueIds()
  1680. {
  1681. System.Collections.Generic.List<PopServerUniqueId> uids = new System.Collections.Generic.List<PopServerUniqueId>();
  1682. string ret = this.CommandMultiline("UIDL");
  1683. string[] lines = ret.Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  1684. foreach (string line in lines)
  1685. {
  1686. string[] parts = line.Split(' ');
  1687. PopServerUniqueId pse =new PopServerUniqueId();
  1688. pse.Index = int.Parse(parts[0]);
  1689. pse.UniqueId = parts[1];
  1690. uids.Add(pse);
  1691. }
  1692. return uids;
  1693. }
  1694. public IAsyncResult BeginGetUniqueIds(AsyncCallback callback)
  1695. {
  1696. this._delegateGetUniqueIDs = this.GetUniqueIds;
  1697. return this._delegateGetUniqueIDs.BeginInvoke(callback, null);
  1698. }
  1699. public System.Collections.Generic.List<PopServerUniqueId> EndGetUniqueIds(IAsyncResult result)
  1700. {
  1701. return this._delegateGetUniqueIDs.EndInvoke(result);
  1702. }
  1703. /// <summary>
  1704. /// Retreives message index on the pop server from its internal unique Id.
  1705. /// </summary>
  1706. /// <param name="serverUniqueId">The given message unique Id to retreive.</param>
  1707. /// <returns>The index of the message on the pop server, 0 if not found.</returns>
  1708. public int GetMessageIndex(string serverUniqueId)
  1709. {
  1710. System.Collections.Generic.List<PopServerUniqueId> uids = this.GetUniqueIds();
  1711. foreach (PopServerUniqueId uid in uids)
  1712. {
  1713. if (uid.UniqueId == serverUniqueId) return uid.Index;
  1714. }
  1715. return 0;
  1716. }
  1717. /// <summary>
  1718. /// Indicates if the uniqueId exists on the server
  1719. /// </summary>
  1720. /// <param name="serverUniqueId">The given message unique Id to retreive.</param>
  1721. /// <returns>True if unique Id exists, False if it doesn't.</returns>
  1722. public bool UniqueIdExists(string serverUniqueId)
  1723. {
  1724. return GetMessageIndex(serverUniqueId) != 0;
  1725. }
  1726. /// <summary>
  1727. /// Structure containing a uniqueId for a message and its associated index on the pop server
  1728. /// </summary>
  1729. public class PopServerUniqueId
  1730. {
  1731. private int _index;
  1732. public int Index
  1733. {
  1734. get
  1735. {
  1736. return this._index;
  1737. }
  1738. set
  1739. {
  1740. this._index = value;
  1741. }
  1742. }
  1743. private string _uniqueId;
  1744. public string UniqueId
  1745. {
  1746. get
  1747. {
  1748. return this._uniqueId;
  1749. }
  1750. set
  1751. {
  1752. this._uniqueId = value;
  1753. }
  1754. }
  1755. }
  1756. /// <summary>
  1757. /// Returns the size of the message at the given index.
  1758. /// </summary>
  1759. /// <param name="messageIndex">Index of the messages.</param>
  1760. /// <returns>The size of the message at the given index.</returns>
  1761. /// <example>
  1762. /// <code>
  1763. /// C#
  1764. ///
  1765. /// Pop3Client pop = new Pop3Client();
  1766. /// pop.Connect("mail.myhost.com","user","pass");
  1767. /// int uniqueId = pop.GetMessageSize(1);
  1768. /// pop.Disconnect();
  1769. ///
  1770. /// VB.NET
  1771. ///
  1772. /// Dim pop As New Pop3Client
  1773. /// pop.Connect("mail.myhost.com","user","pass")
  1774. /// Dim uniqueId As Integer = pop.GetMessageSize(1)
  1775. /// pop.Disconnect()
  1776. ///
  1777. /// JScript.NET
  1778. ///
  1779. /// var pop:Pop3Client = new Pop3Client();
  1780. /// pop.Connect("mail.myhost.com","user","pass");
  1781. /// uniqueId:int = pop.GetMessageSize(1);
  1782. /// pop.Disconnect();
  1783. /// </code>
  1784. /// </example>
  1785. public int GetMessageSize(int messageIndex)
  1786. {
  1787. string myline = this.Command("LIST " + messageIndex.ToString());
  1788. //string myline = this.ReadLine();
  1789. if (!myline.StartsWith("+OK")) throw new ActiveUp.Net.Mail.Pop3Exception("LIST", myline);
  1790. else return System.Convert.ToInt32(myline.Split(' ')[2]);
  1791. }
  1792. public IAsyncResult BeginGetMessageSize(int messageIndex, AsyncCallback callback)
  1793. {
  1794. this._delegateGetMessageSize = this.GetMessageSize;
  1795. return this._delegateGetMessageSize.BeginInvoke(messageIndex, callback, null);
  1796. }
  1797. public int EndGetMessageSize(IAsyncResult result)
  1798. {
  1799. return this._delegateGetMessageSize.EndInvoke(result);
  1800. }
  1801. public void UpdateStats()
  1802. {
  1803. string response = this.Command("STAT");
  1804. //ActiveUp.Net.Mail.Logger.AddEntry(response);
  1805. this.MessageCount = Convert.ToInt32(response.Split(' ')[1]);
  1806. this.TotalSize = Convert.ToInt64(response.Split(' ')[2]);
  1807. }
  1808. public IAsyncResult BeginUpdateStats(AsyncCallback callback)
  1809. {
  1810. this._delegateUpdateStats = this.UpdateStats;
  1811. return this._delegateUpdateStats.BeginInvoke(callback, null);
  1812. }
  1813. public void EndUpdateStats(IAsyncResult result)
  1814. {
  1815. this._delegateUpdateStats.EndInvoke(result);
  1816. }
  1817. /// <summary>
  1818. /// Performs a NOOP command on the server. The aim of this command is to keep the connection alive.
  1819. /// </summary>
  1820. /// <example>
  1821. /// <code>
  1822. /// C#
  1823. ///
  1824. /// Pop3Client pop = new Pop3Client();
  1825. /// pop.Connect("mail.myhost.com","user","pass");
  1826. /// pop.Noop();
  1827. /// pop.Disconnect();
  1828. ///
  1829. /// VB.NET
  1830. ///
  1831. /// Dim pop As New Pop3Client
  1832. /// pop.Connect("mail.myhost.com","user","pass")
  1833. /// pop.Noop()
  1834. /// pop.Disconnect()
  1835. ///
  1836. /// JScript.NET
  1837. ///
  1838. /// var pop:Pop3Client = new Pop3Client();
  1839. /// pop.Connect("mail.myhost.com","user","pass");
  1840. /// pop.Noop();
  1841. /// pop.Disconnect();
  1842. /// </code>
  1843. /// </example>
  1844. public void Noop()
  1845. {
  1846. this.OnNooping();
  1847. this.Command("NOOP");
  1848. this.OnNooped();
  1849. }
  1850. public IAsyncResult BeginNoop(AsyncCallback callback)
  1851. {
  1852. this._delegateNoop = this.Noop;
  1853. return this._delegateNoop.BeginInvoke(callback, null);
  1854. }
  1855. public void EndNoop(IAsyncResult result)
  1856. {
  1857. this._delegateNoop.EndInvoke(result);
  1858. }
  1859. /// <summary>
  1860. /// Checks if specified host has APOP capability.
  1861. /// </summary>
  1862. /// <param name="host">Host to be checked.</param>
  1863. /// <param name="port">Port to connect on to the host.</param>
  1864. /// <returns>True is remote server has APOP, otherwise false.</returns>
  1865. /// <example>
  1866. /// <code>
  1867. /// C#
  1868. ///
  1869. /// bool serverHasAPOP = Pop3Client.CheckAPOP("mail.myhost.com",8503);
  1870. ///
  1871. /// VB.NET
  1872. ///
  1873. /// Dim serverHasAPOP As Boolen = Pop3Client.CheckAPOP("mail.myhost.com",8503)
  1874. ///
  1875. /// JScript.NET
  1876. ///
  1877. /// var serverHasAPOP:bool Pop3Client.CheckAPOP("mail.myhost.com",8503);
  1878. /// </code>
  1879. /// </example>
  1880. public static bool CheckAPOP(string host, int port)
  1881. {
  1882. System.Net.Sockets.TcpClient _tcp = new System.Net.Sockets.TcpClient(host, port);
  1883. byte[] buf = new byte[256];
  1884. _tcp.GetStream().Read(buf, 0, 256);
  1885. //string resp = System.Text.Encoding.ASCII.GetString(buf);
  1886. #if !PocketPC
  1887. string resp = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(buf,0,buf.Length);
  1888. #else
  1889. string resp = PPCEncode.GetString(buf, 0, buf.Length);
  1890. #endif
  1891. _tcp.Close();
  1892. if (resp.IndexOf("<") != -1 && resp.IndexOf(">") != -1 && (resp.IndexOf("@") < resp.IndexOf(">")) && (resp.IndexOf("@") > resp.IndexOf("<"))) return true;
  1893. else return false;
  1894. }
  1895. /// <see cref="CheckAPOP"/>
  1896. public static IAsyncResult BeginCheckAPOP(string host, int port, AsyncCallback callback)
  1897. {
  1898. Pop3Client._delegateCheckAPOP = Pop3Client.CheckAPOP;
  1899. return Pop3Client._delegateCheckAPOP.BeginInvoke(host, port, callback, Pop3Client._delegateCheckAPOP);
  1900. }
  1901. /// <summary>
  1902. /// Checks if specified host has APOP capability.
  1903. /// </summary>
  1904. /// <param name="host">Host to be checked.</param>
  1905. /// <returns>True is remote server has APOP, otherwise false.</returns>
  1906. /// <example>
  1907. /// <code>
  1908. /// C#
  1909. ///
  1910. /// bool serverHasAPOP = Pop3Client.CheckAPOP("mail.myhost.com");
  1911. ///
  1912. /// VB.NET
  1913. ///
  1914. /// Dim serverHasAPOP As Boolen = Pop3Client.CheckAPOP("mail.myhost.com")
  1915. ///
  1916. /// JScript.NET
  1917. ///
  1918. /// var serverHasAPOP:bool Pop3Client.CheckAPOP("mail.myhost.com");
  1919. /// </code>
  1920. /// </example>
  1921. public static bool CheckAPOP(string host)
  1922. {
  1923. return Pop3Client.CheckAPOP(host, 110);
  1924. }
  1925. /// <see cref="CheckAPOP"/>
  1926. public static IAsyncResult BeginCheckAPOP(string host, AsyncCallback callback)
  1927. {
  1928. Pop3Client._delegateCheckAPOPString = Pop3Client.CheckAPOP;
  1929. return Pop3Client._delegateCheckAPOPString.BeginInvoke(host, callback, Pop3Client._delegateCheckAPOPString);
  1930. }
  1931. /// <see cref="CheckAPOP"/>
  1932. public static bool EndCheckAPOP(IAsyncResult result)
  1933. {
  1934. return (bool)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  1935. }
  1936. /// <summary>
  1937. /// Gets the server capabilities.
  1938. /// </summary>
  1939. /// <remarks>Server capabilities are returned as an array of lines. Interpretation is left to the user.</remarks>
  1940. /// <returns>An array of strings containing the server capabilities.</returns>
  1941. public string[] GetServerCapabilities()
  1942. {
  1943. #if !PocketPC
  1944. return this.CommandMultiline("CAPA").Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  1945. #else
  1946. return this.CommandMultiline("CAPA").Replace("\r", "").Split(new char[] { '\n' });
  1947. #endif
  1948. }
  1949. /// <see cref="GetServerCapabilities"/>
  1950. public IAsyncResult BeginGetServerCapabilities(AsyncCallback callback)
  1951. {
  1952. this._delegateGetServerCapabilities = this.GetServerCapabilities;
  1953. return this._delegateGetServerCapabilities.BeginInvoke(callback, null);
  1954. }
  1955. /// <see cref="GetServerCapabilities"/>
  1956. public string[] EndGetServerCapabilities(IAsyncResult result)
  1957. {
  1958. return this._delegateGetServerCapabilities.EndInvoke(result);
  1959. }
  1960. #endregion
  1961. #endregion
  1962. #endregion
  1963. }
  1964. #endregion
  1965. }