PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/module/ASC.MailSystem/ClassLibrary/ActiveUp.Net.Imap4/Imap4Client.cs

https://github.com/dc0d/ONLYOFFICE-Server
C# | 1898 lines | 1091 code | 116 blank | 691 comment | 67 complexity | f3db187fe34d47bf5397873f36175010 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 ActiveUp.Net.Mail;
  18. using ActiveUp.Net.Security;
  19. using System.Text;
  20. using System.Security.Cryptography.X509Certificates;
  21. using System.Net.Security;
  22. namespace ActiveUp.Net.Mail
  23. {
  24. #region Imap4Client Object version 2
  25. /// <summary>
  26. /// This class allows communication with an IMAP4 or IMAP4rev1 compatible server.
  27. /// </summary>
  28. #if !PocketPC
  29. [System.Serializable]
  30. #endif
  31. public class Imap4Client : ActiveUp.Net.Common.BaseProtocolClient
  32. {
  33. #region Constructors
  34. public Imap4Client()
  35. {
  36. }
  37. static Imap4Client()
  38. {
  39. _badCommandStrings = new[] {
  40. "\\", //Important this comes first
  41. "\""
  42. };
  43. }
  44. #endregion
  45. #region Private fields
  46. static string[] _badCommandStrings;
  47. private string host, _capabilities;
  48. //#if !PocketPC
  49. // System.Net.Security.SslStream _sslStream;
  50. //#endif
  51. private bool _idleInProgress = false;
  52. #endregion
  53. #region Properties
  54. /// <summary>
  55. /// Server capabilities.
  56. /// </summary>
  57. public string ServerCapabilities
  58. {
  59. get
  60. {
  61. return this._capabilities;
  62. }
  63. set
  64. {
  65. this._capabilities = value;
  66. }
  67. }
  68. /// <summary>
  69. /// Turn this on to not make any parameters safe. Injection attacks more likely. Turn this on only if you are already doing checking or if performance is absolutely critical.
  70. /// </summary>
  71. public bool IsUnsafeParamsAllowed { get; set; }
  72. #endregion
  73. #region Delegates and associated private fields
  74. private delegate string DelegateConnect(string host, int port);
  75. private DelegateConnect _delegateConnect;
  76. private delegate string DelegateConnectAuth(string host, int port, string username, string password);
  77. private DelegateConnectAuth _delegateConnectAuth;
  78. private delegate string DelegateConnectIPAddress(System.Net.IPAddress addr, int port);
  79. private DelegateConnectIPAddress _delegateConnectIPAddress;
  80. private delegate string DelegateConnectIPAddresses(System.Net.IPAddress[] addresses, int port);
  81. private DelegateConnectIPAddresses _delegateConnectIPAddresses;
  82. #if !PocketPC
  83. private delegate string DelegateConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  84. private DelegateConnectSsl _delegateConnectSsl;
  85. private delegate string DelegateConnectSslIPAddress(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  86. private DelegateConnectSslIPAddress _delegateConnectSslIPAddress;
  87. private delegate string DelegateConnectSslIPAddresses(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake);
  88. private DelegateConnectSslIPAddresses _delegateConnectSslIPAddresses;
  89. #endif
  90. private delegate string DelegateDisconnect();
  91. private DelegateDisconnect _delegateDisconnect;
  92. private delegate string DelegateAuthenticate(string username, string password, SaslMechanism mechanism);
  93. private DelegateAuthenticate _delegateAuthenticate;
  94. private delegate string DelegateLogin(string username, string password, string host);
  95. private DelegateLogin _delegateLogin;
  96. private delegate string DelegateCommand(string command, string stamp, CommandOptions options);
  97. private DelegateCommand _delegateCommand;
  98. private delegate string DelegateCommandStringStringString(string command, string stamp, string checkStamp, CommandOptions options);
  99. private DelegateCommandStringStringString _delegateCommandStringStringString;
  100. private delegate string DelegateNoop();
  101. private DelegateNoop _delegateNoop;
  102. private delegate string DelegateCheck();
  103. private DelegateCheck _delegateCheck;
  104. private delegate string DelegateClose();
  105. private DelegateClose _delegateClose;
  106. private delegate void DelegateExpunge();
  107. private DelegateExpunge _delegateExpunge;
  108. private delegate Mailbox DelegateMailboxOperation(string mailboxName);
  109. private DelegateMailboxOperation _delegateMailboxOperation;
  110. private delegate string DelegateRenameMailbox(string oldMailboxName, string newMailboxName);
  111. private DelegateRenameMailbox _delegateRenameMailbox;
  112. private delegate string DelegateMailboxOperationReturnsString(string mailboxName);
  113. private DelegateMailboxOperationReturnsString _delegateMailboxOperationReturnsString;
  114. private delegate MailboxCollection DelegateGetMailboxes(string reference, string mailboxName);
  115. private DelegateGetMailboxes _delegateGetMailboxes;
  116. #endregion
  117. #region Events
  118. #region Event definitions
  119. /// <summary>
  120. /// Event fired when authentication starts.
  121. /// </summary>
  122. public event ActiveUp.Net.Mail.AuthenticatingEventHandler Authenticating;
  123. /// <summary>
  124. /// Event fired when authentication completed.
  125. /// </summary>
  126. public event ActiveUp.Net.Mail.AuthenticatedEventHandler Authenticated;
  127. /// <summary>
  128. /// Event fired when NOOP command is issued.
  129. /// </summary>
  130. public event ActiveUp.Net.Mail.NoopingEventHandler Nooping;
  131. /// <summary>
  132. /// Event fired when NOOP command completed.
  133. /// </summary>
  134. public event ActiveUp.Net.Mail.NoopedEventHandler Nooped;
  135. /// <summary>
  136. /// Event fired when a command is being written to the server.
  137. /// </summary>
  138. public event ActiveUp.Net.Mail.TcpWritingEventHandler TcpWriting;
  139. /// <summary>
  140. /// Event fired when a command has been written to the server.
  141. /// </summary>
  142. public event ActiveUp.Net.Mail.TcpWrittenEventHandler TcpWritten;
  143. /// <summary>
  144. /// Event fired when a response is being read from the server.
  145. /// </summary>
  146. public event ActiveUp.Net.Mail.TcpReadingEventHandler TcpReading;
  147. /// <summary>
  148. /// Event fired when a response has been read from the server.
  149. /// </summary>
  150. public event ActiveUp.Net.Mail.TcpReadEventHandler TcpRead;
  151. /// <summary>
  152. /// Event fired when a message is being requested using the RetrieveMessage() method.
  153. /// </summary>
  154. public event ActiveUp.Net.Mail.MessageRetrievingEventHandler MessageRetrieving;
  155. /// <summary>
  156. /// Event fired when a message is being retrieved using the RetrieveMessage() method.
  157. /// </summary>
  158. public event ActiveUp.Net.Mail.MessageRetrievedEventHandler MessageRetrieved;
  159. /// <summary>
  160. /// Event fired when a message Header is being requested using the RetrieveHeader() method.
  161. /// </summary>
  162. public event ActiveUp.Net.Mail.HeaderRetrievingEventHandler HeaderRetrieving;
  163. /// <summary>
  164. /// Event fired when a message Header has been retrieved using the RetrieveHeader() method.
  165. /// </summary>
  166. public event ActiveUp.Net.Mail.HeaderRetrievedEventHandler HeaderRetrieved;
  167. /// <summary>
  168. /// Event fired when attempting to connect to the remote server using the specified host.
  169. /// </summary>
  170. public event ActiveUp.Net.Mail.ConnectingEventHandler Connecting;
  171. /// <summary>
  172. /// Event fired when the object is connected to the remote server or when connection failed.
  173. /// </summary>
  174. public new event ActiveUp.Net.Mail.ConnectedEventHandler Connected;
  175. /// <summary>
  176. /// Event fired when attempting to disconnect from the remote server.
  177. /// </summary>
  178. public event ActiveUp.Net.Mail.DisconnectingEventHandler Disconnecting;
  179. /// <summary>
  180. /// Event fired when the object disconnected from the remote server.
  181. /// </summary>
  182. public event ActiveUp.Net.Mail.DisconnectedEventHandler Disconnected;
  183. /// <summary>
  184. /// Event fired when a message is being sent.
  185. /// </summary>
  186. public event ActiveUp.Net.Mail.MessageSendingEventHandler MessageSending;
  187. /// <summary>
  188. /// Event fired when a message has been sent.
  189. /// </summary>
  190. public event ActiveUp.Net.Mail.MessageSentEventHandler MessageSent;
  191. /// <summary>
  192. /// Event fired when a new message received.
  193. /// </summary>
  194. public event ActiveUp.Net.Mail.NewMessageReceivedEventHandler NewMessageReceived;
  195. #endregion
  196. #region Event triggers and logging
  197. internal void OnAuthenticating(ActiveUp.Net.Mail.AuthenticatingEventArgs e)
  198. {
  199. if (Authenticating != null) Authenticating(this, e);
  200. ActiveUp.Net.Mail.Logger.AddEntry("Authenticating as " + e.Username + " on " + e.Host + "...", 2);
  201. }
  202. internal void OnAuthenticated(ActiveUp.Net.Mail.AuthenticatedEventArgs e)
  203. {
  204. if (Authenticated != null) Authenticated(this, e);
  205. ActiveUp.Net.Mail.Logger.AddEntry("Authenticated as " + e.Username + " on " + e.Host + ".", 2);
  206. }
  207. internal void OnNooping()
  208. {
  209. if (Nooping != null) Nooping(this);
  210. ActiveUp.Net.Mail.Logger.AddEntry("Nooping...", 1);
  211. }
  212. internal void OnNooped()
  213. {
  214. if (Nooped != null) Nooped(this);
  215. ActiveUp.Net.Mail.Logger.AddEntry("Nooped.", 1);
  216. }
  217. internal void OnTcpWriting(ActiveUp.Net.Mail.TcpWritingEventArgs e)
  218. {
  219. if (TcpWriting != null) TcpWriting(this, e);
  220. ActiveUp.Net.Mail.Logger.AddEntry("Sending " + e.Command + "...", 1);
  221. }
  222. internal void OnTcpWritten(ActiveUp.Net.Mail.TcpWrittenEventArgs e)
  223. {
  224. if (TcpWritten != null) TcpWritten(this, e);
  225. ActiveUp.Net.Mail.Logger.AddEntry("Sent " + e.Command + ".", 1);
  226. }
  227. internal void OnTcpReading()
  228. {
  229. if (TcpReading != null) TcpReading(this);
  230. ActiveUp.Net.Mail.Logger.AddEntry("Reading...", 1);
  231. }
  232. internal void OnTcpRead(ActiveUp.Net.Mail.TcpReadEventArgs e)
  233. {
  234. if (TcpRead != null) TcpRead(this, e);
  235. ActiveUp.Net.Mail.Logger.AddEntry("Read " + e.Response + ".", 1);
  236. }
  237. internal void OnMessageRetrieving(ActiveUp.Net.Mail.MessageRetrievingEventArgs e)
  238. {
  239. if (MessageRetrieving != null) MessageRetrieving(this, e);
  240. ActiveUp.Net.Mail.Logger.AddEntry("Retrieving message at index " + e.MessageIndex + "...", 2);
  241. }
  242. internal void OnMessageRetrieved(ActiveUp.Net.Mail.MessageRetrievedEventArgs e)
  243. {
  244. if (MessageRetrieved != null) MessageRetrieved(this, e);
  245. ActiveUp.Net.Mail.Logger.AddEntry("Retrieved message at index " + e.MessageIndex + ".", 2);
  246. }
  247. internal void OnHeaderRetrieving(ActiveUp.Net.Mail.HeaderRetrievingEventArgs e)
  248. {
  249. if (HeaderRetrieving != null) HeaderRetrieving(this, e);
  250. ActiveUp.Net.Mail.Logger.AddEntry("Retrieving Header at index " + e.MessageIndex + "...", 2);
  251. }
  252. internal void OnHeaderRetrieved(ActiveUp.Net.Mail.HeaderRetrievedEventArgs e)
  253. {
  254. if (HeaderRetrieved != null) HeaderRetrieved(this, e);
  255. ActiveUp.Net.Mail.Logger.AddEntry("Retrieved Header at index " + e.MessageIndex + ".", 2);
  256. }
  257. internal void OnDisconnecting()
  258. {
  259. if (Disconnecting != null) Disconnecting(this);
  260. ActiveUp.Net.Mail.Logger.AddEntry("Disconnecting...", 2);
  261. }
  262. internal void OnDisconnected(ActiveUp.Net.Mail.DisconnectedEventArgs e)
  263. {
  264. if (Disconnected != null) Disconnected(this, e);
  265. ActiveUp.Net.Mail.Logger.AddEntry("Disconnected.", 2);
  266. }
  267. internal void OnConnecting()
  268. {
  269. if (Connecting != null) Connecting(this);
  270. ActiveUp.Net.Mail.Logger.AddEntry("Connecting...", 2);
  271. }
  272. internal void OnConnected(ActiveUp.Net.Mail.ConnectedEventArgs e)
  273. {
  274. if (Connected != null) Connected(this, e);
  275. ActiveUp.Net.Mail.Logger.AddEntry("Connected. Server replied : " + e.ServerResponse + ".", 2);
  276. }
  277. internal void OnMessageSending(ActiveUp.Net.Mail.MessageSendingEventArgs e)
  278. {
  279. if (MessageSending != null) MessageSending(this, e);
  280. ActiveUp.Net.Mail.Logger.AddEntry("Sending message with subject : " + e.Message.Subject + "...", 2);
  281. }
  282. internal void OnMessageSent(ActiveUp.Net.Mail.MessageSentEventArgs e)
  283. {
  284. if (MessageSent != null) MessageSent(this, e);
  285. ActiveUp.Net.Mail.Logger.AddEntry("Sent message with subject : " + e.Message.Subject + "...", 2);
  286. }
  287. internal void OnNewMessageReceived(ActiveUp.Net.Mail.NewMessageReceivedEventArgs e)
  288. {
  289. if (NewMessageReceived != null) NewMessageReceived(this, e);
  290. ActiveUp.Net.Mail.Logger.AddEntry("New message received : " + e.MessageCount + "...", 2);
  291. }
  292. #endregion
  293. #endregion
  294. #region Methods
  295. #region Private utility methods
  296. private string _CramMd5(string username, string password)
  297. {
  298. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password));
  299. string stamp = System.DateTime.Now.ToString("yyMMddhhmmss" + System.DateTime.Now.Millisecond.ToString());
  300. byte[] data = System.Convert.FromBase64String(this.Command(stamp + " authenticate cram-md5", stamp).Split(' ')[1].Trim(new char[] { '\r', '\n' }));
  301. string digest = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
  302. string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username + " " + ActiveUp.Net.Mail.Crypto.HMACMD5Digest(password, digest))), stamp);
  303. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, response));
  304. return response;
  305. }
  306. private string _Login(string username, string password)
  307. {
  308. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password));
  309. string stamp = System.DateTime.Now.ToString("yyMMddhhmmss" + System.DateTime.Now.Millisecond.ToString());
  310. this.Command("authenticate login"); ;
  311. this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username)), stamp);
  312. string response = this.Command(System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(password)), stamp);
  313. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, response));
  314. return response;
  315. }
  316. private static string FindLine(string[] input, string pattern)
  317. {
  318. foreach (string str in input) if (str.IndexOf(pattern) != -1) return str;
  319. return "";
  320. }
  321. #if !PocketPC
  322. protected override void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
  323. {
  324. this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false, sslHandShake.ServerCertificateValidationCallback, sslHandShake.ClientCertificateSelectionCallback);
  325. bool authenticationFailed = false;
  326. try
  327. {
  328. this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
  329. }
  330. catch (Exception)
  331. {
  332. authenticationFailed = true;
  333. }
  334. if (authenticationFailed)
  335. {
  336. //System.Net.ServicePointManager.CertificatePolicy' is obsolete: 'CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead.
  337. //System.Net.ServicePointManager.CertificatePolicy = new ActiveUp.Net.Security.TrustAllCertificatePolicy();
  338. System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CertValidation);
  339. this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates, sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
  340. }
  341. }
  342. bool CertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyErrors)
  343. { // Trust all certificate policy
  344. return true;
  345. }
  346. #endif
  347. private string ReadLine()
  348. {
  349. this.OnTcpReading();
  350. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), true);
  351. string response = sr.ReadLine();
  352. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs(response));
  353. return response;
  354. }
  355. /// <summary>
  356. /// Takes a command parameter and makes it safe for IMAP
  357. /// </summary>
  358. /// <param name="commandParam"></param>
  359. /// <returns></returns>
  360. private string renderSafeParam(string commandParam)
  361. {
  362. if (this.IsUnsafeParamsAllowed)
  363. return commandParam;
  364. var sb = new StringBuilder(commandParam);
  365. foreach (var badString in _badCommandStrings)
  366. sb.Replace(badString, "\\" + badString);
  367. return sb.ToString();
  368. }
  369. #endregion
  370. #region Public methods
  371. #region Connecting, authenticating and disconnecting
  372. #region Cleartext methods
  373. /// <summary>
  374. /// Connects to the server.
  375. /// </summary>
  376. /// <param name="host">Server address.</param>
  377. /// <returns>The server's response greeting.</returns>
  378. /// <example>
  379. /// <code>
  380. /// C#
  381. ///
  382. /// Imap4Client imap = new Imap4Client();
  383. /// imap.Connect("mail.myhost.com");
  384. /// ...
  385. ///
  386. /// VB.NET
  387. ///
  388. /// Dim imap As New Imap4Client
  389. /// imap.Connect("mail.myhost.com")
  390. /// ...
  391. ///
  392. /// JScript.NET
  393. ///
  394. /// var imap:Imap4Client imap = new Imap4Client();
  395. /// imap.Connect("mail.myhost.com");
  396. /// ...
  397. /// </code>
  398. /// </example>
  399. public string Connect(string host)
  400. {
  401. return this.Connect(host, 143);
  402. }
  403. /// <summary>
  404. /// Begins the connect.
  405. /// </summary>
  406. /// <param name="host">The host.</param>
  407. /// <param name="callback">The callback.</param>
  408. /// <returns></returns>
  409. public IAsyncResult BeginConnect(string host, AsyncCallback callback)
  410. {
  411. this._delegateConnect = this.Connect;
  412. return this._delegateConnect.BeginInvoke(host, 143, callback, this._delegateConnect);
  413. }
  414. /// <summary>
  415. /// Connects to the server.
  416. /// </summary>
  417. /// <param name="host">Server address.</param>
  418. /// <param name="port">Server port.</param>
  419. /// <returns>The server's response greeting.</returns>
  420. /// <example>
  421. /// <code>
  422. /// C#
  423. ///
  424. /// Imap4Client imap = new Imap4Client();
  425. /// imap.Connect("mail.myhost.com",8505);
  426. /// ...
  427. ///
  428. /// VB.NET
  429. ///
  430. /// Dim imap As New Imap4Client
  431. /// imap.Connect("mail.myhost.com",8505)
  432. /// ...
  433. ///
  434. /// JScript.NET
  435. ///
  436. /// var imap:Imap4Client imap = new Imap4Client();
  437. /// imap.Connect("mail.myhost.com",8505);
  438. /// ...
  439. /// </code>
  440. /// </example>
  441. public new string Connect(string host, int port)
  442. {
  443. this.host = host;
  444. this.OnConnecting();
  445. base.Connect(host, port);
  446. string response = this.ReadLine();
  447. this.ServerCapabilities = this.Command("capability");
  448. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  449. return response;
  450. }
  451. public string ConnectTLS(string host, int port)
  452. {
  453. this.Connect(host, port);
  454. //this.SendEhloHelo();
  455. return this.StartTLS(host);
  456. }
  457. /// <summary>
  458. /// Begins the connect.
  459. /// </summary>
  460. /// <param name="host">The host.</param>
  461. /// <param name="port">The port.</param>
  462. /// <param name="callback">The callback.</param>
  463. /// <returns></returns>
  464. public override IAsyncResult BeginConnect(string host, int port, AsyncCallback callback)
  465. {
  466. this._delegateConnect = this.Connect;
  467. return this._delegateConnect.BeginInvoke(host, port, callback, this._delegateConnect);
  468. }
  469. public IAsyncResult BeginConnectTLS(string host, int port, AsyncCallback callback)
  470. {
  471. this._delegateConnect = this.ConnectTLS;
  472. return this._delegateConnect.BeginInvoke(host, port, callback, this._delegateConnect);
  473. }
  474. /// <summary>
  475. /// Connects the specified addr.
  476. /// </summary>
  477. /// <param name="addr">The addr.</param>
  478. /// <param name="port">The port.</param>
  479. /// <returns></returns>
  480. public new string Connect(System.Net.IPAddress addr, int port)
  481. {
  482. this.OnConnecting();
  483. base.Connect(addr, port);
  484. string response = this.ReadLine();
  485. this.ServerCapabilities = this.Command("capability");
  486. this.OnConnected(new ConnectedEventArgs(response));
  487. return response;
  488. }
  489. /// <summary>
  490. /// Begins the connect.
  491. /// </summary>
  492. /// <param name="addr">The addr.</param>
  493. /// <param name="port">The port.</param>
  494. /// <param name="callback">The callback.</param>
  495. /// <returns></returns>
  496. public IAsyncResult BeginConnect(System.Net.IPAddress addr, int port, AsyncCallback callback)
  497. {
  498. this._delegateConnectIPAddress = this.Connect;
  499. return this._delegateConnectIPAddress.BeginInvoke(addr, port, callback, this._delegateConnectIPAddress);
  500. }
  501. /// <summary>
  502. /// Connects the specified addresses.
  503. /// </summary>
  504. /// <param name="addresses">The addresses.</param>
  505. /// <param name="port">The port.</param>
  506. /// <returns></returns>
  507. public new string Connect(System.Net.IPAddress[] addresses, int port)
  508. {
  509. this.OnConnecting();
  510. #if !PocketPC
  511. base.Connect(addresses, port);
  512. #else
  513. if(addresses.Length>0)
  514. base.Connect(addresses[0], port);
  515. #endif
  516. string response = this.ReadLine();
  517. this.ServerCapabilities = this.Command("capability");
  518. this.OnConnected(new ConnectedEventArgs(response));
  519. return response;
  520. }
  521. public IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, AsyncCallback callback)
  522. {
  523. this._delegateConnectIPAddresses = this.Connect;
  524. return this._delegateConnectIPAddresses.BeginInvoke(addresses, port, callback, this._delegateConnectIPAddresses);
  525. }
  526. public string Connect(string host, string username, string password)
  527. {
  528. return this.Connect(host, 143, username, password);
  529. }
  530. /// <summary>
  531. /// Begins the connect.
  532. /// </summary>
  533. /// <param name="host">The host.</param>
  534. /// <param name="username">The username.</param>
  535. /// <param name="password">The password.</param>
  536. /// <param name="callback">The callback.</param>
  537. /// <returns></returns>
  538. public IAsyncResult BeginConnect(string host, string username, string password, AsyncCallback callback)
  539. {
  540. return this.BeginConnect(host, 143, username, password, callback);
  541. }
  542. /// <summary>
  543. /// Connects the specified host.
  544. /// </summary>
  545. /// <param name="host">The host.</param>
  546. /// <param name="port">The port.</param>
  547. /// <param name="username">The username.</param>
  548. /// <param name="password">The password.</param>
  549. /// <returns></returns>
  550. public string Connect(string host, int port, string username, string password)
  551. {
  552. this.Connect(host, port);
  553. return this.LoginFast(username, password, host);
  554. }
  555. /// <summary>
  556. /// Begins the connect.
  557. /// </summary>
  558. /// <param name="host">The host.</param>
  559. /// <param name="port">The port.</param>
  560. /// <param name="username">The username.</param>
  561. /// <param name="password">The password.</param>
  562. /// <param name="callback">The callback.</param>
  563. /// <returns></returns>
  564. public IAsyncResult BeginConnect(string host, int port, string username, string password, AsyncCallback callback)
  565. {
  566. this._delegateConnectAuth = this.Connect;
  567. return this._delegateConnectAuth.BeginInvoke(host, port, username, password, callback, this._delegateConnectAuth);
  568. }
  569. /// <summary>
  570. /// Ends the connect.
  571. /// </summary>
  572. /// <param name="result">The result.</param>
  573. /// <returns></returns>
  574. public new string EndConnect(IAsyncResult result)
  575. {
  576. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  577. }
  578. /// <summary>
  579. /// Gets a value indicating whether this instance is connected.
  580. /// </summary>
  581. /// <value>
  582. /// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
  583. /// </value>
  584. public override bool IsConnected
  585. {
  586. get
  587. {
  588. if (this.Client != null)
  589. return this.Client.Connected;
  590. else
  591. return false;
  592. }
  593. }
  594. #endregion
  595. #region SSL methods
  596. #if !PocketPC
  597. public string ConnectSsl(string host)
  598. {
  599. return this.ConnectSsl(host, 993, new ActiveUp.Net.Security.SslHandShake(host));
  600. }
  601. public IAsyncResult BeginConnectSsl(string host, AsyncCallback callback)
  602. {
  603. return this.BeginConnectSsl(host, 993, new ActiveUp.Net.Security.SslHandShake(host), callback);
  604. }
  605. public string ConnectSsl(string host, ActiveUp.Net.Security.SslHandShake sslHandShake)
  606. {
  607. return this.ConnectSsl(host, 993, sslHandShake);
  608. }
  609. public IAsyncResult BeginConnectSsl(string host, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  610. {
  611. return this.BeginConnectSsl(host, 993, sslHandShake, callback);
  612. }
  613. public string ConnectSsl(string host, int port)
  614. {
  615. return this.ConnectSsl(host, port, new ActiveUp.Net.Security.SslHandShake(host));
  616. }
  617. public override IAsyncResult BeginConnectSsl(string host, int port, AsyncCallback callback)
  618. {
  619. return this.BeginConnectSsl(host, port, new SslHandShake(host), callback);
  620. }
  621. #endif
  622. #if !PocketPC
  623. public string ConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  624. {
  625. this.OnConnecting();
  626. base.Connect(host, port);
  627. this.DoSslHandShake(sslHandShake);
  628. string response = this.ReadLine();
  629. this.ServerCapabilities = this.Command("capability");
  630. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  631. return response;
  632. }
  633. public IAsyncResult BeginConnectSsl(string host, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  634. {
  635. this._delegateConnectSsl = this.ConnectSsl;
  636. return this._delegateConnectSsl.BeginInvoke(host, port, sslHandShake, callback, this._delegateConnectSsl);
  637. }
  638. public string ConnectSsl(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  639. {
  640. this.OnConnecting();
  641. base.Connect(addr, port);
  642. this.DoSslHandShake(sslHandShake);
  643. string response = this.ReadLine();
  644. this.ServerCapabilities = this.Command("capability");
  645. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  646. return response;
  647. }
  648. public IAsyncResult BeginConnectSsl(System.Net.IPAddress addr, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  649. {
  650. this._delegateConnectSslIPAddress = this.ConnectSsl;
  651. return this._delegateConnectSslIPAddress.BeginInvoke(addr, port, sslHandShake, callback, this._delegateConnectSslIPAddress);
  652. }
  653. public string ConnectSsl(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake)
  654. {
  655. this.OnConnecting();
  656. base.Connect(addresses, port);
  657. this.DoSslHandShake(sslHandShake);
  658. string response = this.ReadLine();
  659. this.ServerCapabilities = this.Command("capability");
  660. this.OnConnected(new ActiveUp.Net.Mail.ConnectedEventArgs(response));
  661. return response;
  662. }
  663. public IAsyncResult BeginConnectSsl(System.Net.IPAddress[] addresses, int port, ActiveUp.Net.Security.SslHandShake sslHandShake, AsyncCallback callback)
  664. {
  665. this._delegateConnectSslIPAddresses = this.ConnectSsl;
  666. return this._delegateConnectSslIPAddresses.BeginInvoke(addresses, port, sslHandShake, callback, this._delegateConnectSslIPAddresses);
  667. }
  668. public override string EndConnectSsl(IAsyncResult result)
  669. {
  670. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  671. }
  672. #endif
  673. #endregion
  674. #region Disconnect method
  675. /// <summary>
  676. /// Logs out and closes the connection with the server.
  677. /// </summary>
  678. /// <returns>The server's googbye greeting.</returns>
  679. /// <example>
  680. /// <code>
  681. /// C#
  682. ///
  683. /// Imap4Client imap = new Imap4Client();
  684. /// imap.Connect("mail.myhost.com");
  685. /// imap.Login("jdoe1234","tanstaaf");
  686. /// //Do some work...
  687. /// imap.Disconnect();
  688. ///
  689. /// VB.NET
  690. ///
  691. /// Dim imap As New Imap4Client
  692. /// imap.Connect("mail.myhost.com")
  693. /// imap.Login("jdoe1234","tanstaaf")
  694. /// 'Do some work...
  695. /// imap.Disconnect()
  696. ///
  697. /// JScript.NET
  698. ///
  699. /// var imap:Imap4Client imap = new Imap4Client();
  700. /// imap.Connect("mail.myhost.com");
  701. /// imap.Login("jdoe1234","tanstaaf");
  702. /// //Do some work...
  703. /// imap.Disconnect();
  704. /// </code>
  705. /// </example>
  706. public override string Disconnect()
  707. {
  708. string greeting = this.Command("logout");
  709. base.Close();
  710. return greeting;
  711. }
  712. public IAsyncResult BeginDisconnect(AsyncCallback callback)
  713. {
  714. this._delegateDisconnect = this.Disconnect;
  715. return this._delegateDisconnect.BeginInvoke(callback, null);
  716. }
  717. public string EndDisconnect(IAsyncResult result)
  718. {
  719. return this._delegateDisconnect.EndInvoke(result);
  720. }
  721. #endregion
  722. #region Authentication
  723. /// <summary>
  724. /// Logs in to the specified account.
  725. /// </summary>
  726. /// <param name="username">Username of the account.</param>
  727. /// <param name="password">Password of the account.</param>
  728. /// <returns>The server's response.</returns>
  729. /// <example>
  730. /// <code>
  731. /// C#
  732. ///
  733. /// Imap4Client imap = new Imap4Client();
  734. /// imap.Connect("mail.myhost.com");
  735. /// imap.Login("jdoe1234","tanstaaf");
  736. /// //Do some work...
  737. /// imap.Disconnect();
  738. ///
  739. /// VB.NET
  740. ///
  741. /// Dim imap As New Imap4Client
  742. /// imap.Connect("mail.myhost.com")
  743. /// imap.Login("jdoe1234","tanstaaf")
  744. /// 'Do some work...
  745. /// imap.Disconnect()
  746. ///
  747. /// JScript.NET
  748. ///
  749. /// var imap:Imap4Client imap = new Imap4Client();
  750. /// imap.Connect("mail.myhost.com");
  751. /// imap.Login("jdoe1234","tanstaaf");
  752. /// //Do some work...
  753. /// imap.Disconnect();
  754. /// </code>
  755. /// </example>
  756. public override string Login(string username, string password, string _host)//Todo: remove reundant parameter
  757. {
  758. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password, this.host));
  759. string response = this.Command("login " + username + " " + password);
  760. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, this.host, response));
  761. return response;
  762. }
  763. public string LoginOAuth2(string username, string accessToken)
  764. {
  765. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, accessToken, this.host));
  766. string formatResponse = "user=" + username + "\u0001auth=Bearer " + accessToken + "\u0001\u0001";
  767. string authResponse = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(formatResponse));
  768. string response = this.Command("AUTHENTICATE XOAUTH2 " + authResponse);
  769. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, accessToken, this.host, response));
  770. return response;
  771. }
  772. public IAsyncResult BeginLogin(string username, string password, AsyncCallback callback)
  773. {
  774. this._delegateLogin = this.Login;
  775. return this._delegateLogin.BeginInvoke(username, password, this.host, callback, this._delegateLogin);
  776. }
  777. /// <summary>
  778. /// Same as Login but doesn't load the AllMailboxes and Mailboxes properties of the Imap4Client object, ensuring faster operation.
  779. /// </summary>
  780. /// <param name="username">Username of the account.</param>
  781. /// <param name="password">Password of the account.</param>
  782. /// <returns>The server's response.</returns>
  783. public string LoginFast(string username, string password, string host)
  784. {
  785. this.OnAuthenticating(new ActiveUp.Net.Mail.AuthenticatingEventArgs(username, password, this.host));
  786. string response = this.Command("login " + username + " " + password);
  787. this.OnAuthenticated(new ActiveUp.Net.Mail.AuthenticatedEventArgs(username, password, this.host, response));
  788. return response;
  789. }
  790. public IAsyncResult BeginLoginFast(string username, string password, AsyncCallback callback)
  791. {
  792. this._delegateLogin = this.LoginFast;
  793. return this._delegateLogin.BeginInvoke(username, password, this.host, callback, this._delegateLogin);
  794. }
  795. /// <summary>
  796. /// Authenticates using the given SASL mechanism.
  797. /// </summary>
  798. /// <param name="username">Username to authenticate as.</param>
  799. /// <param name="password">Password.</param>
  800. /// <param name="mechanism">SASL mechanism to be used.</param>
  801. /// <returns>The server's response.</returns>
  802. /// <example>
  803. /// <code>
  804. /// C#
  805. ///
  806. /// Imap4Client imap = new Imap4Client();
  807. /// imap.Connect("mail.myhost.com");
  808. /// imap.Authenticate("user","pass",SASLMechanism.CramMd5);
  809. /// imap.Disconnect();
  810. ///
  811. /// VB.NET
  812. ///
  813. /// Dim imap As New Imap4Client
  814. /// imap.Connect("mail.myhost.com")
  815. /// imap.Authenticate("user","pass",SASLMechanism.CramMd5)
  816. /// imap.Disconnect()
  817. ///
  818. /// JScript.NET
  819. ///
  820. /// var imap:Imap4Client = new Imap4Client();
  821. /// imap.Connect("mail.myhost.com");
  822. /// imap.Authenticate("user","pass",SASLMechanism.CramMd5);
  823. /// imap.Disconnect();
  824. /// </code>
  825. /// </example>
  826. public string Authenticate(string username, string password, ActiveUp.Net.Mail.SaslMechanism mechanism)
  827. {
  828. switch (mechanism)
  829. {
  830. case ActiveUp.Net.Mail.SaslMechanism.CramMd5:
  831. return this._CramMd5(username, password);
  832. case ActiveUp.Net.Mail.SaslMechanism.Login:
  833. return this._Login(username, password);
  834. }
  835. return string.Empty;
  836. }
  837. public override IAsyncResult BeginAuthenticate(string username, string password, SaslMechanism mechanism, AsyncCallback callback)
  838. {
  839. this._delegateAuthenticate = this.Authenticate;
  840. return this._delegateAuthenticate.BeginInvoke(username, password, mechanism, callback, null);
  841. }
  842. public string EndAuthenticate(IAsyncResult result)
  843. {
  844. return this._delegateAuthenticate.EndInvoke(result);
  845. }
  846. #endregion
  847. #region Idle
  848. /// <summary>
  849. /// Start the idle on the mail server.
  850. /// </summary>
  851. public void StartIdle()
  852. {
  853. this.Command("IDLE");
  854. System.IO.StreamReader sr = new System.IO.StreamReader(this.GetStream(), System.Text.Encoding.ASCII);
  855. System.Text.StringBuilder buffer = new System.Text.StringBuilder();
  856. string response = string.Empty;
  857. _idleInProgress = true;
  858. while (true)
  859. {
  860. if (_idleInProgress)
  861. {
  862. this.OnTcpReading();
  863. response = sr.ReadLine();
  864. this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs(response));
  865. if (response.ToUpper().IndexOf("RECENT") > 0)
  866. {
  867. this.OnNewMessageReceived(new NewMessageReceivedEventArgs(int.Parse(response.Split(' ')[1])));
  868. }
  869. #if DEBUG
  870. Console.WriteLine(response);
  871. #endif
  872. }
  873. else
  874. {
  875. this.Command("DONE", string.Empty);
  876. break;
  877. }
  878. }
  879. }
  880. /// <summary>
  881. /// Stop the idle on the imap4 server.
  882. /// </summary>
  883. public void StopIdle()
  884. {
  885. _idleInProgress = false;
  886. }
  887. #endregion
  888. #endregion
  889. #region Command sending, receiving and stream access
  890. /// <summary>
  891. /// Sends the command to the server.
  892. /// The command tag is automatically added.
  893. /// </summary>
  894. /// <param name="command">The command (with arguments if necesary) to be sent.</param>
  895. /// <returns>The server's response.</returns>
  896. /// <example>
  897. /// <code>
  898. /// C#
  899. ///
  900. /// Imap4Client imap = new Imap4Client();
  901. /// imap.Connect("mail.myhost.com");
  902. /// imap.Login("user","pass");
  903. /// imap.Command("select inbox");
  904. /// //Selected mailbox is inbox.
  905. /// imap.Disconnect();
  906. ///
  907. /// VB.NET
  908. ///
  909. /// Dim imap As New Imap4Client
  910. /// imap.Connect("mail.myhost.com")
  911. /// imap.Login("user","pass")
  912. /// imap.Command("select inbox")
  913. /// 'Selected mailbox is inbox.
  914. /// imap.Disconnect()
  915. ///
  916. /// JScript.NET
  917. ///
  918. /// var imap:Imap4Client = new Imap4Client();
  919. /// imap.Connect("mail.myhost.com");
  920. /// imap.Login("user","pass");
  921. /// imap.Command("select inbox");
  922. /// //Selected mailbox is inbox.
  923. /// imap.Disconnect();
  924. /// </code>
  925. /// </example>
  926. public string Command(string command)
  927. {
  928. return Command(command, (CommandOptions)null);
  929. }
  930. public string Command(string command, CommandOptions options)
  931. {
  932. return this.Command(command, System.DateTime.Now.ToString("yyMMddhhmmss" + System.DateTime.Now.Millisecond.ToString()), options);
  933. }
  934. public IAsyncResult BeginCommand(string command, AsyncCallback callback)
  935. {
  936. return this.BeginCommand(command, System.DateTime.Now.ToString("yyMMddhhmmss" + System.DateTime.Now.Millisecond.ToString()), callback);
  937. }
  938. public string Command(string command, string stamp)
  939. {
  940. return Command(command, stamp, (CommandOptions)null);
  941. }
  942. public string Command(string command, string stamp, CommandOptions options)
  943. {
  944. if (options == null)
  945. options = new CommandOptions();
  946. /*if (command.Length < 200) this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n"));
  947. else this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs("long command data"));*/
  948. //base.GetStream().Write(System.Text.Encoding.ASCII.GetBytes(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n\r\n"), 0, stamp.Length + ((stamp.Length > 0) ? 1 : 0) + command.Length + 2);
  949. // Although I have still not read all the relevant code but here it looks that you are
  950. // directly trying to write to the network stream which is incorrect. I have commented your
  951. // line above writing directly to network stream and have slightly changed it to write to
  952. // sslstream. I am unable to biuld this solution as 200+ missing file errors are shown. But
  953. // I have run the NUnit test twice and it is passing succesfully therefore I have not checked
  954. // the reading portion from ssl stream. Theoreticaly decrytpion exception should only get generated
  955. // when there is a problem with reading from ssl stream but may be because direct attempt was made
  956. // to write to Network stream so some how it threw decryption exception.
  957. // please see it run and test it--------Atif
  958. // Complement the Atif changes. Use the flag for !PocketPC config for avoid build errors.
  959. #if !PocketPC
  960. GetStream()
  961. .Write(
  962. Encoding.GetEncoding("iso-8859-1")
  963. .GetBytes(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n\r\n"), 0,
  964. stamp.Length + ((stamp.Length > 0) ? 1 : 0) + command.Length + 2);
  965. #endif
  966. #if PocketPC
  967. GetStream().Write(Encoding.GetEncoding("iso-8859-1").GetBytes(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n\r\n"), 0, stamp.Length + ((stamp.Length > 0) ? 1 : 0) + command.Length + 2);
  968. #endif
  969. OnTcpWritten(command.Length < 200
  970. ? new TcpWrittenEventArgs(stamp + ((stamp.Length > 0) ? " " : "") +
  971. command + "\r\n")
  972. : new TcpWrittenEventArgs("long command data"));
  973. OnTcpReading();
  974. var sr = new System.IO.StreamReader(GetStream(), Encoding.GetEncoding("iso-8859-1"));
  975. var buffer = new StringBuilder();
  976. var command_as_upper = command.ToUpper();
  977. string temp;
  978. string lastline;
  979. while (true)
  980. {
  981. temp = sr.ReadLine();
  982. Logger.AddEntry("bordel : " + temp);
  983. buffer.Append(temp + "\r\n");
  984. if (command_as_upper.StartsWith("LIST") || command_as_upper.StartsWith("XLIST"))
  985. {
  986. if (temp != null && (temp.StartsWith(stamp) || (temp.StartsWith("+ ") && options.IsPlusCmdAllowed)))
  987. {
  988. lastline = temp;
  989. break;
  990. }
  991. }
  992. else if (command_as_upper.StartsWith("DONE"))
  993. {
  994. lastline = temp;
  995. if (lastline != null) stamp = lastline.Split(' ')[0];
  996. break;
  997. }
  998. else if (temp != null)
  999. {
  1000. //Had to remove + check - this was failing when the email contained a line with +
  1001. //Please add comments as to why here, and reimplement differently
  1002. if (temp.StartsWith(stamp) || temp.ToLower().StartsWith("* " + command.Split(' ')[0].ToLower()) ||
  1003. (temp.StartsWith("+ ") && options.IsPlusCmdAllowed))
  1004. {
  1005. lastline = temp;
  1006. break;
  1007. }
  1008. }
  1009. else
  1010. throw new Imap4Exception("Unexpected end of stream");
  1011. }
  1012. var buffer_string = buffer.ToString();
  1013. OnTcpRead(buffer.Length < 200
  1014. ? new TcpReadEventArgs(buffer_string)
  1015. : new TcpReadEventArgs("long data"));
  1016. if (lastline != null &&
  1017. (lastline.StartsWith(stamp + " OK") || temp.ToLower().StartsWith("* " + command.Split(' ')[0].ToLower()) ||
  1018. temp.StartsWith("+ ")))
  1019. return buffer_string;
  1020. var failed_string = string.Format("Command \"{0}\" failed : {1}",
  1021. command.StartsWith("login") ? "LOGIN *****" : command, buffer_string);
  1022. throw new Imap4Exception(failed_string);
  1023. }
  1024. public IAsyncResult BeginCommand(string command, string stamp, AsyncCallback callback)
  1025. {
  1026. return BeginCommand(command, stamp, callback, null);
  1027. }
  1028. public IAsyncResult BeginCommand(string command, string stamp, AsyncCallback callback, CommandOptions options)
  1029. {
  1030. this._delegateCommand = this.Command;
  1031. return this._delegateCommand.BeginInvoke(command, stamp, options, callback, this._delegateCommand);
  1032. }
  1033. public string Command(string command, string stamp, string checkStamp)
  1034. {
  1035. return Command(command, stamp, checkStamp, null);
  1036. }
  1037. public string Command(string command, string stamp, string checkStamp, CommandOptions options)
  1038. {
  1039. if (options == null)
  1040. options = new CommandOptions();
  1041. if (command.Length < 200) this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n"));
  1042. else this.OnTcpWriting(new ActiveUp.Net.Mail.TcpWritingEventArgs("long command data"));
  1043. base.GetStream().Write(System.Text.Encoding.ASCII.GetBytes(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n"), 0, stamp.Length + ((stamp.Length > 0) ? 1 : 0) + command.Length + 2);
  1044. if (command.Length < 200) this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs(stamp + ((stamp.Length > 0) ? " " : "") + command + "\r\n"));
  1045. else this.OnTcpWritten(new ActiveUp.Net.Mail.TcpWrittenEventArgs("long command data"));
  1046. this.OnTcpReading();
  1047. System.IO.StreamReader sr = new System.IO.StreamReader(base.GetStream(), true);
  1048. System.Text.StringBuilder buffer = new System.Text.StringBuilder();
  1049. string temp = "";
  1050. string lastline = "";
  1051. while (true)
  1052. {
  1053. temp = sr.ReadLine();
  1054. buffer.Append(temp + "\r\n");
  1055. if (temp.StartsWith("+ ") && options.IsPlusCmdAllowed)
  1056. {
  1057. lastline = temp;
  1058. break;
  1059. }
  1060. if (temp.StartsWith(checkStamp) || temp.ToLower().StartsWith("* " + command.Split(' ')[0].ToLower()))
  1061. {
  1062. lastline = temp;
  1063. break;
  1064. }
  1065. }
  1066. if (buffer.Length < 200) this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs(buffer.ToString()));
  1067. else this.OnTcpRead(new ActiveUp.Net.Mail.TcpReadEventArgs("long data"));
  1068. if (lastline.StartsWith(checkStamp + " OK") || temp.ToLower().StartsWith("* " + command.Split(' ')[0].ToLower()) || temp.StartsWith("+ ")) return buffer.ToString();
  1069. else throw new ActiveUp.Net.Mail.Imap4Exception("Command \"" + command + "\" failed : " + buffer.ToString());
  1070. }
  1071. public IAsyncResult BeginCommand(string command, string stamp, string checkStamp, AsyncCallback callback)
  1072. {
  1073. return BeginCommand(command, stamp, checkStamp, null);
  1074. }
  1075. public IAsyncResult BeginCommand(string command, string stamp, string checkStamp, AsyncCallback callback, CommandOptions options)
  1076. {
  1077. this._delegateCommandStringStringString = this.Command;
  1078. return this._delegateCommandStringStringString.BeginInvoke(command, stamp, checkStamp, options, callback, this._delegateCommandStringStringString);
  1079. }
  1080. public string EndCommand(IAsyncResult result)
  1081. {
  1082. return (string)result.AsyncState.GetType().GetMethod("EndInvoke").Invoke(result.AsyncState, new object[] { result });
  1083. }
  1084. /// <summary>
  1085. /// Gets the communacation stream of this object.
  1086. /// </summary>
  1087. /// <returns>A Stream object, either of type NetworkStream or SslStream if the channel is secured.</returns>
  1088. // public new System.IO.Stream GetStream()
  1089. // {
  1090. //#if !PocketPC
  1091. // if (this._sslStream != null) return this._sslStream;
  1092. //#endif
  1093. // return base.GetStream();
  1094. // }
  1095. /// <summary>
  1096. /// Imap STARTTLS. more info http://tools.ietf.org/html/rfc2595
  1097. /// </summary>
  1098. /// <param name="host"></param>
  1099. /// <returns></returns>
  1100. public override string StartTLS(string host)
  1101. {
  1102. try
  1103. {
  1104. var response = this.Command("STARTTLS");
  1105. this.DoSslHandShake(new ActiveUp.Net.Security.SslHandShake(host));
  1106. response = this.Command("capability");
  1107. return response;
  1108. }
  1109. catch
  1110. {
  1111. return "Not supported";
  1112. }
  1113. }
  1114. #endregion
  1115. #region Implementation of the IMAP4 protocol
  1116. /// <summary>
  1117. /// Performs a NOOP command which is used to maintain the connection alive.
  1118. /// </summary>
  1119. /// <returns>The server response.</returns>
  1120. /// <remarks>Some servers include mailbox update informations in the response.</remarks>
  1121. /// <example>
  1122. /// <code>
  1123. /// C#
  1124. ///
  1125. /// Imap4Client imap = new Imap4Client();
  1126. /// imap.Connect("mail.myhost.com");
  1127. /// try
  1128. /// {
  1129. /// imap.Noop();
  1130. /// imap.Disconnect();
  1131. /// }
  1132. /// catch
  1133. /// {
  1134. /// throw new Exception("Connection lost.");
  1135. /// }
  1136. ///
  1137. /// VB.NET
  1138. ///
  1139. /// Dim imap As New Imap4Client
  1140. /// imap.Connect("mail.myhost.com")
  1141. /// Try
  1142. /// imap.Noop()
  1143. /// imap.Disconnect()
  1144. /// Catch
  1145. /// Throw New Exception("Connection lost.");
  1146. /// End Try
  1147. ///
  1148. /// JScript.NET
  1149. ///
  1150. /// var imap:Imap4Client imap = new Imap4Client();
  1151. /// imap.Connect("mail.myhost.com");
  1152. /// try
  1153. /// {
  1154. /// imap.Noop();
  1155. /// imap.Disconnect();
  1156. /// }
  1157. /// catch
  1158. /// {
  1159. /// throw new Exception("Connection lost.");
  1160. /// }
  1161. /// </code>
  1162. /// </example>
  1163. public string Noop()
  1164. {
  1165. this.OnNooping();
  1166. string response = this.Command("noop");
  1167. this.OnNooped();
  1168. return response;
  1169. }
  1170. public IAsyncResult BeginNoop(AsyncCallback callback)
  1171. {
  1172. this._delegateNoop = this.Noop;
  1173. return this._delegateNoop.BeginInvoke(callback, this._delegateNoop);
  1174. }
  1175. public string EndNoop(IAsyncResult result)
  1176. {
  1177. return this._delegateNoop.EndInvoke(result);
  1178. }
  1179. /// <summary>
  1180. /// Equivalent to Noop().
  1181. /// </summary>
  1182. /// <returns>The server's response.</returns>
  1183. public string Check()
  1184. {
  1185. return this.Command("check");
  1186. }
  1187. public IAsyncResult BeginCheck(AsyncCallback callback)
  1188. {
  1189. this._delegateCheck = this.Check;
  1190. return this._delegateCheck.BeginInvoke(callback, this._delegateCheck);
  1191. }
  1192. public string EndCheck(IAsyncResult result)
  1193. {
  1194. return this._delegateCheck.EndInvoke(result);
  1195. }
  1196. /// <summary>
  1197. /// Closes the mailbox and removes messages marked with the Deleted flag.
  1198. /// </summary>
  1199. /// <returns>The server's response.</returns>
  1200. /// <example>
  1201. /// <code>
  1202. /// C#
  1203. ///
  1204. /// Imap4Client imap = new Imap4Client();
  1205. /// imap.Connect("mail.myhost.com");
  1206. /// imap.Login("jdoe1234","tanstaaf");
  1207. /// Mailbox inbox = imap.SelectInbox("inbox");
  1208. /// //Get the amount of messages in the inbox.
  1209. /// int messageCount = inbox.MessageCount;
  1210. /// inbox.Close();
  1211. /// imap.Disconnect();
  1212. ///
  1213. /// VB.NET
  1214. ///
  1215. /// Dim imap As New Imap4Client
  1216. /// imap.Connect("mail.myhost.com")
  1217. /// imap.Login("jdoe1234","tanstaaf")
  1218. /// Dim inbox As Mailbox = imap.SelectInbox("inbox")
  1219. /// //Get the amount of messages in the inbox.
  1220. /// Dim messageCount As Integer = inbox.MessageCount
  1221. /// inbox.Close()
  1222. /// imap.Disconnect()
  1223. ///
  1224. /// JScript.NET
  1225. ///
  1226. /// var imap:Imap4Client imap = new Imap4Client();
  1227. /// imap.Connect("mail.myhost.com");
  1228. /// imap.Login("jdoe1234","tanstaaf");
  1229. /// var inbox:Mailbox = imap.SelectInbox("inbox");
  1230. /// //Get the amount of messages in the inbox.
  1231. /// var messageCount:int = inbox.MessageCount;
  1232. /// inbox.Close();
  1233. /// imap.Disconnect();
  1234. /// </code>
  1235. /// </example>
  1236. public new string Close()
  1237. {
  1238. return this.Command("close");
  1239. }
  1240. public IAsyncResult BeginClose(AsyncCallback callback)
  1241. {
  1242. this._delegateClose = this.Close;
  1243. return this._delegateClose.BeginInvoke(callback, this._delegateClose);
  1244. }
  1245. public string EndClose(IAsyncResult result)
  1246. {
  1247. return this._delegateClose.EndInvoke(result);
  1248. }
  1249. /// <summary>
  1250. /// Removes all messages marked with the Deleted flag.
  1251. /// </summary>
  1252. /// <example>
  1253. /// <code>
  1254. /// C#
  1255. ///
  1256. /// Imap4Client imap = new Imap4Client();
  1257. /// imap.Connect("mail.myhost.com");
  1258. /// imap.Login("jdoe1234","tanstaaf");
  1259. /// Mailbox inbox = imap.SelectInbox("inbox");
  1260. /// //Mark message 1 for deletion.
  1261. /// inbox.DeleteMessage(1);
  1262. /// //Effectively remove all message marked with Deleted flag.
  1263. /// imap.Expunge();
  1264. /// //Message 1 is permanently removed.
  1265. /// imap.Disconnect();
  1266. ///
  1267. /// VB.NET
  1268. ///
  1269. /// Dim imap As New Imap4Client
  1270. /// imap.Connect("mail.myhost.com")
  1271. /// imap.Login("jdoe1234","tanstaaf")
  1272. /// Dim inbox As Mailbox = imap.SelectInbox("inbox")
  1273. /// 'Mark message 1 for deletion.
  1274. /// inbox.DeleteMessage(1)
  1275. /// 'Effectively remove all message marked with Deleted flag.
  1276. /// imap.Expunge()
  1277. /// 'Message 1 is permanently removed.
  1278. /// imap.Disconnect()
  1279. ///
  1280. /// JScript.NET
  1281. ///
  1282. /// var imap:Imap4Client imap = new Imap4Client();
  1283. /// imap.Connect("mail.myhost.com");
  1284. /// imap.Login("jdoe1234","tanstaaf");
  1285. /// var inbox:Mailbox = imap.SelectInbox("inbox");
  1286. /// //Mark message 1 for deletion.
  1287. /// inbox.DeleteMessage(1);
  1288. /// //Effectively remove all message marked with Deleted flag.
  1289. /// imap.Expunge();
  1290. /// //Message 1 is permanently removed.
  1291. /// imap.Disconnect();
  1292. /// </code>
  1293. /// </example>
  1294. public void Expunge()
  1295. {
  1296. this.Command("expunge");
  1297. }
  1298. public IAsyncResult BeginExpunge(AsyncCallback callback)
  1299. {
  1300. this._delegateExpunge = this.Expunge;
  1301. return this._delegateExpunge.BeginInvoke(callback, this._delegateExpunge);
  1302. }
  1303. public void EndExpunge(IAsyncResult result)
  1304. {
  1305. this._delegateExpunge.EndInvoke(result);
  1306. }
  1307. /// <summary>
  1308. /// Retrieves a list of mailboxes.
  1309. /// </summary>
  1310. /// <param name="reference">The base path.</param>
  1311. /// <param name="mailboxName">Mailbox name.</param>
  1312. /// <returns>A MailboxCollection object containing the requested mailboxes.</returns>
  1313. /// <example>
  1314. /// <code>
  1315. /// C#
  1316. ///
  1317. /// Imap4Client imap = new Imap4Client();
  1318. /// imap.Connect("mail.myhost.com");
  1319. /// imap.Login("user","pass");
  1320. /// //Return all children mailboxes of "inbox".
  1321. /// MailboxCollection mailboxes = imap.GetMailboxes("inbox","*");
  1322. /// imap.Disconnect();
  1323. ///
  1324. /// VB.NET
  1325. ///
  1326. /// Dim imap As New Imap4Client
  1327. /// imap.Connect("mail.myhost.com")
  1328. /// imap.Login("user","pass")
  1329. /// 'Return all children mailboxes of "inbox".
  1330. /// Dim mailboxes As MailboxCollection = imap.GetMailboxes("inbox","*")
  1331. /// imap.Disconnect()
  1332. ///
  1333. /// JScript.NET
  1334. ///
  1335. /// var imap:Imap4Client = new Imap4Client();
  1336. /// imap.Connect("mail.myhost.com");
  1337. /// imap.Login("user","pass");
  1338. /// //Return all children mailboxes of "inbox".
  1339. /// var mailboxes:MailboxCollection = imap.GetMailboxes("inbox","*");
  1340. /// imap.Disconnect();
  1341. /// </code>
  1342. /// </example>
  1343. public MailboxCollection GetMailboxes(string reference, string mailboxName)
  1344. {
  1345. MailboxCollection mailboxes = new MailboxCollection();
  1346. string response = this.Command("list \"" + reference + "\" \"" + mailboxName + "\"");
  1347. string[] t = System.Text.RegularExpressions.Regex.Split(response, "\r\n");
  1348. string box = "";
  1349. for (int i = 0; i < t.Length - 2; i++)
  1350. {
  1351. try
  1352. {
  1353. box = t[i].Substring(t[i].IndexOf("\" ") + 1).Trim(new char[] { ' ', '\"' });
  1354. if (box != reference && reference.ToLower() != (box.ToLower() + "/")) mailboxes.Add(this.ExamineMailbox(box));
  1355. }
  1356. catch { continue; }
  1357. }
  1358. return mailboxes;
  1359. }
  1360. public IAsyncResult BeginGetMailboxes(string reference, string mailboxName, AsyncCallback callback)
  1361. {
  1362. this._delegateGetMailboxes = this.GetMailboxes;
  1363. return this._delegateGetMailboxes.BeginInvoke(reference, mailboxName, callback, this._delegateGetMailboxes);
  1364. }
  1365. public MailboxCollection EndGetMailboxes(IAsyncResult result)
  1366. {
  1367. return this._delegateGetMailboxes.EndInvoke(result);
  1368. }
  1369. /// <summary>
  1370. /// Creates a mailbox with the specified name.
  1371. /// </summary>
  1372. /// <param name="mailboxName">The name of the new mailbox.</param>
  1373. /// <returns>The newly created mailbox.</returns>
  1374. /// <example>
  1375. /// <code>
  1376. /// C#
  1377. ///
  1378. /// Imap4Client imap = new Imap4Client();
  1379. /// imap.Connect("mail.myhost.com");
  1380. /// imap.Login("user","pass");
  1381. /// imap.CreateMailbox("inbox.Staff");
  1382. /// //Child mailbox of inbox named Staff has been created.
  1383. /// imap.Disconnect();
  1384. ///
  1385. /// VB.NET
  1386. ///
  1387. /// Dim imap As New Imap4Client
  1388. /// imap.Connect("mail.myhost.com")
  1389. /// imap.Login("user","pass")
  1390. /// imap.CreateMailbox("inbox.Staff");
  1391. /// 'Child mailbox of inbox named Staff has been created.
  1392. /// imap.Disconnect()
  1393. ///
  1394. /// JScript.NET
  1395. ///
  1396. /// var imap:Imap4Client = new Imap4Client();
  1397. /// imap.Connect("mail.myhost.com");
  1398. /// imap.Login("user","pass");
  1399. /// imap.CreateMailbox("inbox.Staff");
  1400. /// //Child mailbox of inbox named Staff has been created.
  1401. /// imap.Disconnect();
  1402. /// </code>
  1403. /// </example>
  1404. public Mailbox CreateMailbox(string mailboxName)
  1405. {
  1406. this.Command("create \"" + mailboxName + "\"");
  1407. return this.SelectMailbox(mailboxName);
  1408. }
  1409. public IAsyncResult BeginCreateMailbox(string mailboxName, AsyncCallback callback)
  1410. {
  1411. this._delegateMailboxOperation = this.CreateMailbox;
  1412. return this._delegateMailboxOperation.BeginInvoke(mailboxName, callback, this._delegateMailboxOperation);
  1413. }
  1414. public Mailbox EndCreateMailbox(IAsyncResult result)
  1415. {
  1416. return this._delegateMailboxOperation.EndInvoke(result);
  1417. }
  1418. /// <summary>
  1419. /// Renames a mailbox.
  1420. /// </summary>
  1421. /// <param name="oldMailboxName">The mailbox to be renamed.</param>
  1422. /// <param name="newMailboxName">The new name of the mailbox.</param>
  1423. /// <returns>The server's response.</returns>
  1424. /// <example>
  1425. /// <code>
  1426. /// C#
  1427. ///
  1428. /// Imap4Client imap = new Imap4Client();
  1429. /// imap.Connect("mail.myhost.com");
  1430. /// imap.Login("user","pass");
  1431. /// imap.RenameMailbox("inbox.Staff","Staff");
  1432. /// //The Staff mailbox is now a top-level mailbox.
  1433. /// imap.Disconnect();
  1434. ///
  1435. /// VB.NET
  1436. ///
  1437. /// Dim imap As New Imap4Client
  1438. /// imap.Connect("mail.myhost.com")
  1439. /// imap.Login("user","pass")
  1440. /// imap.RenameMailbox("inbox.Staff","Staff");
  1441. /// 'The Staff mailbox is now a top-level mailbox.
  1442. /// imap.Disconnect()
  1443. ///
  1444. /// JScript.NET
  1445. ///
  1446. /// var imap:Imap4Client = new Imap4Client();
  1447. /// imap.Connect("mail.myhost.com");
  1448. /// imap.Login("user","pass");
  1449. /// imap.RenameMailbox("inbox.Staff","Staff");
  1450. /// //The Staff mailbox is now a top-level mailbox.
  1451. /// imap.Disconnect();
  1452. /// </code>
  1453. /// </example>
  1454. public string RenameMailbox(string oldMailboxName, string newMailboxName)
  1455. {
  1456. string response = this.Command("rename \"" + oldMailboxName + "\" \"" + newMailboxName + "\"");
  1457. return response;
  1458. }
  1459. public IAsyncResult BeginRenameMailbox(string oldMailboxName, string newMailboxName, AsyncCallback callback)
  1460. {
  1461. this._delegateRenameMailbox = this.RenameMailbox;
  1462. return this._delegateRenameMailbox.BeginInvoke(oldMailboxName, newMailboxName, callback, this._delegateRenameMailbox);
  1463. }
  1464. public void EndRenameMailbox(IAsyncResult result)
  1465. {
  1466. this._delegateRenameMailbox.EndInvoke(result);
  1467. }
  1468. /// <summary>
  1469. /// Deletes a mailbox.
  1470. /// </summary>
  1471. /// <param name="mailboxName">The mailbox to be deleted.</param>
  1472. /// <returns>The server's response.</returns>
  1473. /// <example>
  1474. /// <code>
  1475. /// C#
  1476. ///
  1477. /// Imap4Client imap = new Imap4Client();
  1478. /// imap.Connect("mail.myhost.com");
  1479. /// imap.Login("user","pass");
  1480. /// imap.DeleteMailbox("inbox.Staff");
  1481. /// //The inbox.Staff mailbox is now deleted.
  1482. /// imap.Disconnect();
  1483. ///
  1484. /// VB.NET
  1485. ///
  1486. /// Dim imap As New Imap4Client
  1487. /// imap.Connect("mail.myhost.com")
  1488. /// imap.Login("user","pass")
  1489. /// imap.DeleteMailbox("inbox.Staff");
  1490. /// //The inbox.Staff mailbox is now deleted.
  1491. /// imap.Disconnect()
  1492. ///
  1493. /// JScript.NET
  1494. ///
  1495. /// var imap:Imap4Client = new Imap4Client();
  1496. /// imap.Connect("mail.myhost.com");
  1497. /// imap.Login("user","pass");
  1498. /// imap.DeleteMailbox("inbox.Staff");
  1499. /// //The inbox.Staff mailbox is now deleted.
  1500. /// imap.Disconnect();
  1501. /// </code>
  1502. /// </example>
  1503. public string DeleteMailbox(string mailboxName)
  1504. {
  1505. return this.Command("delete \"" + mailboxName + "\"");
  1506. }
  1507. public IAsyncResult BeginDeleteMailbox(string mailboxName, AsyncCallback callback)
  1508. {
  1509. this._delegateMailboxOperationReturnsString = this.DeleteMailbox;
  1510. return this._delegateMailboxOperationReturnsString.BeginInvoke(mailboxName, callback, this._delegateMailboxOperationReturnsString);
  1511. }
  1512. public string EndDeleteMailbox(IAsyncResult result)
  1513. {
  1514. return this._delegateMailboxOperationReturnsString.EndInvoke(result);
  1515. }
  1516. /// <summary>
  1517. /// Subscribes to a mailbox.
  1518. /// </summary>
  1519. /// <param name="mailboxName">The mailbox to be subscribed to.</param>
  1520. /// <returns>The server's response.</returns>
  1521. public string SubscribeMailbox(string mailboxName)
  1522. {
  1523. return this.Command("subscribe \"" + mailboxName + "\"");
  1524. }
  1525. public IAsyncResult BeginSubscribeMailbox(string mailboxName, AsyncCallback callback)
  1526. {
  1527. this._delegateMailboxOperationReturnsString = this.SubscribeMailbox;
  1528. return this._delegateMailboxOperationReturnsString.BeginInvoke(mailboxName, callback, this._delegateMailboxOperationReturnsString);
  1529. }
  1530. public void EndSubscribeMailbox(IAsyncResult result)
  1531. {
  1532. this._delegateMailboxOperationReturnsString.EndInvoke(result);
  1533. }
  1534. /// <summary>
  1535. /// Unsubscribes from a mailbox.
  1536. /// </summary>
  1537. /// <param name="mailboxName">The mailbox to be unsubscribed from.</param>
  1538. /// <returns>The server's response.</returns>
  1539. public string UnsubscribeMailbox(string mailboxName)
  1540. {
  1541. return this.Command("unsubscribe \"" + mailboxName + "\"");
  1542. }
  1543. public IAsyncResult BeginUnsubscribeMailbox(string mailboxName, AsyncCallback callback)
  1544. {
  1545. this._delegateMailboxOperationReturnsString = this.UnsubscribeMailbox;
  1546. return this._delegateMailboxOperationReturnsString.BeginInvoke(mailboxName, callback, this._delegateMailboxOperationReturnsString);
  1547. }
  1548. public void EndUnsubscribeMailbox(IAsyncResult result)
  1549. {
  1550. this._delegateMailboxOperationReturnsString.EndInvoke(result);
  1551. }
  1552. /// <summary>
  1553. /// Selects a mailbox on the server.
  1554. /// </summary>
  1555. /// <param name="mailboxName">The mailbox to be selected.</param>
  1556. /// <returns>The selected mailbox.</returns>
  1557. /// <example>
  1558. /// <code>
  1559. /// C#
  1560. ///
  1561. /// Imap4Client imap = new Imap4Client();
  1562. /// imap.Connect("mail.myhost.com");
  1563. /// imap.Login("user","pass");
  1564. /// Mailbox mbox = imap.SelectMailbox("inbox.Staff");
  1565. /// //The inbox.Staff mailbox is now selected.
  1566. /// mbox.Empty(true);
  1567. /// //Mailbox inbox.Staff is now empty.
  1568. /// imap.Disconnect();
  1569. ///
  1570. /// VB.NET
  1571. ///
  1572. /// Dim imap As New Imap4Client
  1573. /// imap.Connect("mail.myhost.com")
  1574. /// imap.Login("user","pass")
  1575. /// Dim mbox As Mailbox = imap.SelectMailbox("inbox.Staff")
  1576. /// 'The inbox.Staff mailbox is now selected.
  1577. /// mbox.Empty(true)
  1578. /// 'Mailbox inbox.Staff is now empty.
  1579. /// imap.Disconnect()
  1580. ///
  1581. /// JScript.NET
  1582. ///
  1583. /// var imap:Imap4Client = new Imap4Client();
  1584. /// imap.Connect("mail.myhost.com");
  1585. /// imap.Login("user","pass");
  1586. /// var mbox:Mailbox = imap.SelectMailbox("inbox.Staff");
  1587. /// //The inbox.Staff mailbox is now selected.
  1588. /// mbox.Empty(true);
  1589. /// //Mailbox inbox.Staff is now empty.
  1590. /// imap.Disconnect();
  1591. /// </code>
  1592. /// </example>
  1593. public Mailbox SelectMailbox(string mailboxName)
  1594. {
  1595. mailboxName = renderSafeParam(mailboxName);
  1596. ActiveUp.Net.Mail.Mailbox mailbox = new ActiveUp.Net.Mail.Mailbox();
  1597. string response = this.Command("select \"" + mailboxName + "\"");
  1598. string[] lines = System.Text.RegularExpressions.Regex.Split(response, "\r\n");
  1599. // message count.
  1600. int messageCount = 0;
  1601. try { messageCount = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "EXISTS").Split(' ')[1]); }
  1602. catch (Exception) { }
  1603. mailbox.MessageCount = messageCount;
  1604. // recent.
  1605. int recent = 0;
  1606. try { recent = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "RECENT").Split(' ')[1]); }
  1607. catch (Exception) { }
  1608. mailbox.Recent = recent;
  1609. // unseen.
  1610. int unseen = 0;
  1611. try { unseen = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UNSEEN ").Split(' ')[3].TrimEnd(']')); }
  1612. catch (Exception) { }
  1613. mailbox.FirstUnseen = (response.ToLower().IndexOf("[unseen") != -1) ? unseen : 0;
  1614. // uid validity.
  1615. int uidValidity = 0;
  1616. try { uidValidity = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UIDVALIDITY ").Split(' ')[3].TrimEnd(']')); }
  1617. catch (Exception) { }
  1618. mailbox.UidValidity = uidValidity;
  1619. // flags.
  1620. foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, " FLAGS").Split(' '))
  1621. {
  1622. if (str.StartsWith("(\\") || str.StartsWith("\\"))
  1623. {
  1624. mailbox.ApplicableFlags.Add(str.Trim(new char[] { ' ', '\\', ')', '(' }));
  1625. }
  1626. }
  1627. // permanent flags.
  1628. if (response.ToLower().IndexOf("[permanentflags") != -1)
  1629. {
  1630. foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[PERMANENTFLAGS").Split(' '))
  1631. {
  1632. if (str.StartsWith("(\\") || str.StartsWith("\\"))
  1633. {
  1634. mailbox.PermanentFlags.Add(str.Trim(new char[] { ' ', '\\', ')', '(' }));
  1635. }
  1636. }
  1637. }
  1638. // read-write and read-only.
  1639. if (response.ToLower().IndexOf("[read-write]") != -1)
  1640. {
  1641. mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadWrite;
  1642. }
  1643. else if (response.ToLower().IndexOf("[read-only]") != -1)
  1644. {
  1645. mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadOnly;
  1646. }
  1647. mailbox.Name = mailboxName;
  1648. mailbox.SourceClient = this;
  1649. return mailbox;
  1650. }
  1651. public IAsyncResult BeginSelectMailbox(string mailboxName, AsyncCallback callback)
  1652. {
  1653. this._delegateMailboxOperation = this.SelectMailbox;
  1654. return this._delegateMailboxOperation.BeginInvoke(mailboxName, callback, this._delegateMailboxOperation);
  1655. }
  1656. public Mailbox EndSelectMailbox(IAsyncResult result)
  1657. {
  1658. return this._delegateMailboxOperation.EndInvoke(result);
  1659. }
  1660. /// <summary>
  1661. /// Same as SelectMailbox() except that the mailbox is opened with read-only permission.
  1662. /// </summary>
  1663. /// <param name="mailboxName">The mailbox to be examined.</param>
  1664. /// <returns>The examined mailbox.</returns>
  1665. /// <example>
  1666. /// <code>
  1667. /// C#
  1668. ///
  1669. /// Imap4Client imap = new Imap4Client();
  1670. /// imap.Connect("mail.myhost.com");
  1671. /// imap.Login("user","pass");
  1672. /// Mailbox mbox = imap.ExamineMailbox("inbox.Staff");
  1673. /// //The inbox.Staff mailbox is now selected (read-only).
  1674. /// int recentMessageCount = mbox.Recent;
  1675. /// //There are recentMessageCount messages that haven't been read in inbox.Staff.
  1676. /// imap.Disconnect();
  1677. ///
  1678. /// VB.NET
  1679. ///
  1680. /// Dim imap As New Imap4Client
  1681. /// imap.Connect("mail.myhost.com")
  1682. /// imap.Login("user","pass")
  1683. /// Dim mbox As Mailbox = imap.ExamineMailbox("inbox.Staff")
  1684. /// 'The inbox.Staff mailbox is now selected (read-only).
  1685. /// Dim recentMessageCount As Integer = mbox.Recent
  1686. /// 'There are recentMessageCount messages that haven't been read in inbox.Staff.
  1687. /// imap.Disconnect()
  1688. ///
  1689. /// JScript.NET
  1690. ///
  1691. /// var imap:Imap4Client = new Imap4Client();
  1692. /// imap.Connect("mail.myhost.com");
  1693. /// imap.Login("user","pass");
  1694. /// var mbox:Mailbox = imap.ExamineMailbox("inbox.Staff");
  1695. /// //The inbox.Staff mailbox is now selected (read-only).
  1696. /// int recentMessageCount = mbox.Recent;
  1697. /// //There are recentMessageCount messages that haven't been read in inbox.Staff.
  1698. /// imap.Disconnect();
  1699. /// </code>
  1700. /// </example>
  1701. public Mailbox ExamineMailbox(string mailboxName)
  1702. {
  1703. ActiveUp.Net.Mail.Mailbox mailbox = new ActiveUp.Net.Mail.Mailbox();
  1704. string response = this.Command("examine \"" + mailboxName + "\"");
  1705. string[] lines = System.Text.RegularExpressions.Regex.Split(response, "\r\n");
  1706. mailbox.MessageCount = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "EXISTS").Split(' ')[1]);
  1707. mailbox.Recent = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "RECENT").Split(' ')[1]);
  1708. mailbox.FirstUnseen = (response.ToLower().IndexOf("[unseen") != -1) ? System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UNSEEN ").Split(' ')[3].TrimEnd(']')) : 0;
  1709. mailbox.UidValidity = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UIDVALIDITY ").Split(' ')[3].TrimEnd(']'));
  1710. foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, " FLAGS").Split(' ')) if (str.StartsWith("(\\") || str.StartsWith("\\")) mailbox.ApplicableFlags.Add(str.Trim(new char[] { ' ', '\\', ')', '(' }));
  1711. if (response.ToLower().IndexOf("[permanentflags") != -1) foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[PERMANENTFLAGS").Split(' ')) if (str.StartsWith("(\\") || str.StartsWith("\\")) mailbox.PermanentFlags.Add(str.Trim(new char[] { ' ', '\\', ')', '(' }));
  1712. mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadOnly;
  1713. mailbox.Name = mailboxName;
  1714. mailbox.SourceClient = this;
  1715. return mailbox;
  1716. }
  1717. public IAsyncResult BeginExamineMailbox(string mailboxName, AsyncCallback callback)
  1718. {
  1719. this._delegateMailboxOperation = this.ExamineMailbox;
  1720. return this._delegateMailboxOperation.BeginInvoke(mailboxName, callback, this._delegateMailboxOperation);
  1721. }
  1722. public Mailbox EndExamineMailbox(IAsyncResult result)
  1723. {
  1724. return this._delegateMailboxOperation.EndInvoke(result);
  1725. }
  1726. #endregion
  1727. #endregion
  1728. #endregion
  1729. }
  1730. #endregion
  1731. }