forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImapClient.cs
2293 lines (2222 loc) · 105 KB
/
ImapClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using S22.Imap.Auth;
using S22.Imap.Auth.Sasl;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
namespace S22.Imap {
/// <summary>
/// Enables applications to communicate with a mail server using the Internet Message Access
/// Protocol (IMAP).
/// </summary>
public class ImapClient : IImapClient
{
Stream stream;
TcpClient client;
bool disposed;
readonly object readLock = new object();
readonly object writeLock = new object();
readonly object sequenceLock = new object();
string[] capabilities;
int tag = 0;
string selectedMailbox;
string defaultMailbox = "INBOX";
event EventHandler<IdleMessageEventArgs> newMessageEvent;
event EventHandler<IdleMessageEventArgs> messageDeleteEvent;
bool hasEvents {
get {
return newMessageEvent != null || messageDeleteEvent != null;
}
}
bool idling;
Thread idleThread, idleDispatch;
int pauseRefCount = 0;
SafeQueue<string> idleEvents = new SafeQueue<string>();
System.Timers.Timer noopTimer = new System.Timers.Timer();
static readonly TraceSource ts = new TraceSource("S22.Imap");
/// <summary>
/// The default mailbox to operate on.
/// </summary>
/// <exception cref="ArgumentNullException">The property is being set and the value is
/// null.</exception>
/// <exception cref="ArgumentException">The property is being set and the value is the empty
/// string.</exception>
/// <remarks>The default value for this property is "INBOX" which is a special name reserved
/// to mean "the primary mailbox for this user on this server".</remarks>
public string DefaultMailbox {
get {
return defaultMailbox;
}
set {
value.ThrowIfNullOrEmpty();
defaultMailbox = value;
}
}
/// <summary>
/// Determines whether the client is authenticated with the server.
/// </summary>
public bool Authed {
get;
private set;
}
/// <summary>
/// The event that is raised when a new mail message has been received by the server.
/// </summary>
/// <remarks>To probe a server for IMAP IDLE support, the <see cref="Supports"/>
/// method can be used, specifying "IDLE" for the capability parameter.
///
/// Please note that the event handler will be executed on a threadpool thread.
/// </remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="NewMessage"]/*'/>
public event EventHandler<IdleMessageEventArgs> NewMessage {
add {
newMessageEvent += value;
StartIdling();
}
remove {
newMessageEvent -= value;
if (!hasEvents)
StopIdling();
}
}
/// <summary>
/// The event that is raised when a message has been deleted on the server.
/// </summary>
/// <remarks>To probe a server for IMAP IDLE support, the <see cref="Supports"/>
/// method can be used, specifying "IDLE" for the capability parameter.
///
/// Please note that the event handler will be executed on a threadpool thread.
/// </remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="MessageDeleted"]/*'/>
public event EventHandler<IdleMessageEventArgs> MessageDeleted {
add {
messageDeleteEvent += value;
StartIdling();
}
remove {
messageDeleteEvent -= value;
if (!hasEvents)
StopIdling();
}
}
/// <summary>
/// The event that is raised when an I/O exception occurs in the idle-thread.
/// </summary>
/// <remarks>
/// An I/O exception can occur if the underlying network connection has been reset or the
/// server unexpectedly closed the connection.
/// </remarks>
public event EventHandler<IdleErrorEventArgs> IdleError;
/// <summary>
/// This constructor is solely used for unit testing.
/// </summary>
/// <param name="stream">A stream to initialize the ImapClient instance with.</param>
internal ImapClient(Stream stream) {
this.stream = stream;
Authed = true;
}
/// <summary>
/// Initializes a new instance of the ImapClient class and connects to the specified port
/// on the specified host, optionally using the Secure Socket Layer (SSL) security protocol.
/// </summary>
/// <param name="hostname">The DNS name of the server to which you intend to connect.</param>
/// <param name="port">The port number of the server to which you intend to connect.</param>
/// <param name="ssl">Set to true to use the Secure Socket Layer (SSL) security protocol.</param>
/// <param name="validate">Delegate used for verifying the remote Secure Sockets
/// Layer (SSL) certificate which is used for authentication. Can be null if not needed.</param>
/// <exception cref="ArgumentOutOfRangeException">The port parameter is not between MinPort
/// and MaxPort.</exception>
/// <exception cref="ArgumentNullException">The hostname parameter is null.</exception>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server upon connecting.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="SocketException">An error occurred while accessing the socket used for
/// establishing the connection to the IMAP server. Use the ErrorCode property to obtain the
/// specific error code.</exception>
/// <exception cref="System.Security.Authentication.AuthenticationException">An authentication
/// error occured while trying to establish a secure connection.</exception>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="ctor-1"]/*'/>
public ImapClient(string hostname, int port = 143, bool ssl = false,
RemoteCertificateValidationCallback validate = null) {
Connect(hostname, port, ssl, validate);
}
/// <summary>
/// Initializes a new instance of the ImapClient class and connects to the specified port on
/// the specified host, optionally using the Secure Socket Layer (SSL) security protocol and
/// attempts to authenticate with the server using the specified authentication method and
/// credentials.
/// </summary>
/// <param name="hostname">The DNS name of the server to which you intend to connect.</param>
/// <param name="port">The port number of the server to which you intend to connect.</param>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <param name="method">The requested method of authentication. Can be one of the values
/// of the AuthMethod enumeration.</param>
/// <param name="ssl">Set to true to use the Secure Socket Layer (SSL) security protocol.</param>
/// <param name="validate">Delegate used for verifying the remote Secure Sockets Layer
/// (SSL) certificate which is used for authentication. Can be null if not needed.</param>
/// <exception cref="ArgumentOutOfRangeException">The port parameter is not between MinPort
/// and MaxPort.</exception>
/// <exception cref="ArgumentNullException">The hostname parameter is null.</exception>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server upon connecting.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="InvalidCredentialsException">The provided credentials were rejected by the
/// server.</exception>
/// <exception cref="SocketException">An error occurred while accessing the socket used for
/// establishing the connection to the IMAP server. Use the ErrorCode property to obtain the
/// specific error code.</exception>
/// <exception cref="System.Security.Authentication.AuthenticationException">An authentication
/// error occured while trying to establish a secure connection.</exception>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="ctor-2"]/*'/>
public ImapClient(string hostname, int port, string username, string password, AuthMethod method =
AuthMethod.Auto, bool ssl = false, RemoteCertificateValidationCallback validate = null) {
Connect(hostname, port, ssl, validate);
Login(username, password, method);
}
/// <summary>
/// Connects to the specified port on the specified host, optionally using the Secure Socket Layer
/// (SSL) security protocol.
/// </summary>
/// <param name="hostname">The DNS name of the server to which you intend to connect.</param>
/// <param name="port">The port number of the server to which you intend to connect.</param>
/// <param name="ssl">Set to true to use the Secure Socket Layer (SSL) security protocol.</param>
/// <param name="validate">Delegate used for verifying the remote Secure Sockets Layer (SSL)
/// certificate which is used for authentication. Can be null if not needed.</param>
/// <exception cref="ArgumentOutOfRangeException">The port parameter is not between MinPort
/// and MaxPort.</exception>
/// <exception cref="ArgumentNullException">The hostname parameter is null.</exception>
/// <exception cref="BadServerResponseException">An unexpected response has been received
/// from the server upon connecting.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="SocketException">An error occurred while accessing the socket used for
/// establishing the connection to the IMAP server. Use the ErrorCode property to obtain the
/// specific error code.</exception>
/// <exception cref="System.Security.Authentication.AuthenticationException">An authentication
/// error occured while trying to establish a secure connection.</exception>
void Connect(string hostname, int port, bool ssl, RemoteCertificateValidationCallback validate) {
client = new TcpClient(hostname, port);
stream = client.GetStream();
if (ssl) {
SslStream sslStream = new SslStream(stream, false, validate ??
((sender, cert, chain, err) => true));
sslStream.AuthenticateAsClient(hostname);
stream = sslStream;
}
// The server issues an untagged OK greeting upon connect.
string greeting = GetResponse();
if (!IsResponseOK(greeting))
throw new BadServerResponseException(greeting);
}
/// <summary>
/// Determines whether the specified response is a valid IMAP OK response.
/// </summary>
/// <param name="response">A response string received from the server.</param>
/// <param name="tag">A tag if the response is associated with a command.</param>
/// <returns>true if the response is a valid IMAP OK response; Otherwise false.</returns>
bool IsResponseOK(string response, string tag = null) {
if (tag != null)
return response.StartsWith(tag + "OK");
string v = response.Substring(response.IndexOf(' ')).Trim();
return v.StartsWith("OK");
}
/// <summary>
/// Attempts to establish an authenticated session with the server using the specified
/// credentials.
/// </summary>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <param name="method">The requested method of authentication. Can be one of the values
/// of the AuthMethod enumeration.</param>
/// <exception cref="ArgumentNullException">The username parameter or the password parameter
/// is null.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="InvalidCredentialsException">The server rejected the supplied
/// credentials.</exception>
/// <exception cref="NotSupportedException">The specified authentication method is not
/// supported by the server.</exception>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Login"]/*'/>
public void Login(string username, string password, AuthMethod method) {
username.ThrowIfNull("username");
password.ThrowIfNull("password");
string tag = GetTag(), response;
switch (method) {
case AuthMethod.Login:
response = Login(tag, username, password);
break;
case AuthMethod.Auto:
response = AuthAuto(tag, username, password);
break;
case AuthMethod.NtlmOverSspi:
response = SspiAuthenticate(tag, username, password, true);
break;
case AuthMethod.Gssapi:
response = SspiAuthenticate(tag, username, password, false);
break;
default:
response = Authenticate(tag, username, password, method.ToString());
break;
}
// The server may include an untagged CAPABILITY line in the response.
if (response.StartsWith("* CAPABILITY")) {
capabilities = response.Substring(13).Trim().Split(' ')
.Select(s => s.ToUpperInvariant()).ToArray();
response = GetResponse();
}
if (!IsResponseOK(response, tag))
throw new InvalidCredentialsException(response);
Authed = true;
}
/// <summary>
/// Performs authentication using the most secure authentication mechanism supported by the
/// server.
/// </summary>
/// <param name="tag">The tag identifier to use for performing the authentication
/// commands.</param>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <returns>The response sent by the server.</returns>
/// <remarks>The order of preference of authentication types employed by this method is
/// Ntlm, Scram-Sha-1, Digest-Md5, followed by Cram-Md5 and finally plaintext Login as
/// a last resort.</remarks>
string AuthAuto(string tag, string username, string password) {
string[] methods = new string[] { "Srp", "Ntlm", "ScramSha1", "DigestMd5",
"CramMd5" };
foreach (string m in methods) {
try {
string response = Authenticate(tag, username, password, m);
if (IsResponseOK(response, tag) || response.StartsWith("* CAPABILITY"))
return response;
} catch {
// Go on with next method.
}
}
// If all of the above failed, use login as a last resort.
return Login(tag, username, password);
}
/// <summary>
/// Performs an actual IMAP "LOGIN" command using the specified username and plain-text
/// password.
/// </summary>
/// <param name="tag">The tag identifier to use for performing the authentication
/// commands.</param>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <returns>The response sent by the server.</returns>
string Login(string tag, string username, string password) {
return SendCommandGetResponse(tag + "LOGIN " + username.QuoteString() +
" " + password.QuoteString());
}
/// <summary>
/// Performs NTLM and Kerberos authentication via the Security Support Provider Interface (SSPI).
/// </summary>
/// <param name="tag">The tag identifier to use for performing the authentication
/// commands.</param>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <param name="useNtlm">True to authenticate using NTLM, otherwise GSSAPI (Kerberos) is
/// used.</param>
/// <returns>The response sent by the server.</returns>
/// <exception cref="NotSupportedException">The specified authentication method is not
/// supported by the server.</exception>
string SspiAuthenticate(string tag, string username, string password,
bool useNtlm) {
string response = SendCommandGetResponse(tag + "AUTHENTICATE " + (useNtlm ?
"NTLM" : "GSSAPI"));
// If we get a BAD or NO response, the mechanism is not supported.
if (response.StartsWith(tag + "BAD") || response.StartsWith(tag + "NO")) {
throw new NotSupportedException("The requested authentication " +
"mechanism is not supported by the server.");
}
using (FilterStream fs = new FilterStream(stream, true)) {
using (NegotiateStream ns = new NegotiateStream(fs, true)) {
try {
ns.AuthenticateAsClient(
useNtlm && username == String.Empty ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(username, password),
null,
String.Empty,
useNtlm ? ProtectionLevel.None : ProtectionLevel.EncryptAndSign,
System.Security.Principal.TokenImpersonationLevel.Delegation);
} catch {
return String.Empty;
}
}
}
response = GetResponse();
// Swallow any continuation data we unexpectedly receive from the server.
while (response.StartsWith("+ "))
response = SendCommandGetResponse(String.Empty);
return response;
}
/// <summary>
/// Performs authentication using a SASL authentication mechanism via IMAP's authenticate
/// command.
/// </summary>
/// <param name="tag">The tag identifier to use for performing the authentication
/// commands.</param>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <param name="mechanism">The name of the SASL authentication mechanism to use.</param>
/// <returns>The response sent by the server.</returns>
/// <exception cref="SaslException">The authentication mechanism with the specified name could
/// not be found.</exception>
/// <exception cref="NotSupportedException">The specified authentication mechanism is not
/// supported by the server.</exception>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server.</exception>
string Authenticate(string tag, string username, string password,
string mechanism) {
SaslMechanism m = SaslFactory.Create(mechanism);
if (!Supports("Auth=" + m.Name))
throw new NotSupportedException("The requested authentication " +
"mechanism is not supported by the server.");
m.Properties.Add("Username", username);
m.Properties.Add("Password", password);
// OAuth and OAuth2 use access tokens.
m.Properties.Add("AccessToken", password);
string response = SendCommandGetResponse(tag + "AUTHENTICATE " + m.Name);
// If we get a BAD or NO response, the mechanism is not supported.
if (response.StartsWith(tag + "BAD") || response.StartsWith(tag + "NO")) {
throw new NotSupportedException("The requested authentication " +
"mechanism is not supported by the server.");
}
while (!m.IsCompleted) {
// Annoyingly, Gmail OAUTH2 issues an untagged capability response during the SASL
// authentication process. As per spec this is illegal, but we should still deal with it.
while (response.StartsWith("*"))
response = GetResponse();
// Stop if the server response starts with our tag.
if (response.StartsWith(tag))
break;
// Strip off continuation request '+'-character and possible whitespace.
string challenge = Regex.Replace(response, @"^\+\s?", String.Empty);
// Compute and send off the challenge-response.
response = m.GetResponse(challenge);
response = SendCommandGetResponse(response);
}
return response;
}
/// <summary>
/// Logs an authenticated client out of the server. After the logout sequence has been completed,
/// the server closes the connection with the client.
/// </summary>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server during the logout sequence.</exception>
/// <remarks>Calling this method in non-authenticated state has no effect.</remarks>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
public void Logout() {
AssertValid(false);
if (!Authed)
return;
lock (sequenceLock) {
StopIdling();
string tag = GetTag();
string bye = SendCommandGetResponse(tag + "LOGOUT");
if (!bye.StartsWith("* BYE"))
throw new BadServerResponseException(bye);
string response = GetResponse();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
Authed = false;
}
}
/// <summary>
/// Generates a unique identifier to prefix a command with, as is required by the IMAP protocol.
/// </summary>
/// <returns>A unique identifier string.</returns>
string GetTag() {
Interlocked.Increment(ref tag);
return string.Format("xm{0:000} ", tag);
}
/// <summary>
/// Sends a command string to the server. This method blocks until the command has been
/// transmitted.
/// </summary>
/// <param name="command">The command to send to the server. The string is suffixed by CRLF
/// prior to sending.</param>
void SendCommand(string command) {
ts.TraceInformation("C -> " + command);
// We can safely use UTF-8 here since it's backwards compatible with ASCII and comes in handy
// when sending strings in literal form (see RFC 3501, 4.3).
byte[] bytes = Encoding.UTF8.GetBytes(command + "\r\n");
lock (writeLock) {
stream.Write(bytes, 0, bytes.Length);
}
}
/// <summary>
/// Sends a command string to the server and subsequently waits for a response, which is then
/// returned to the caller. This method blocks until the server response has been received.
/// </summary>
/// <param name="command">The command to send to the server. This is suffixed by CRLF prior
/// to sending.</param>
/// <param name="resolveLiterals">Set to true to resolve possible literals returned by the
/// server (Refer to RFC 3501 Section 4.3 for details).</param>
/// <returns>The response received by the server.</returns>
string SendCommandGetResponse(string command, bool resolveLiterals = true) {
lock (readLock) {
lock (writeLock) {
SendCommand(command);
}
return GetResponse(resolveLiterals);
}
}
/// <summary>
/// Waits for a response from the server. This method blocks until a response has been received.
/// </summary>
/// <param name="resolveLiterals">Set to true to resolve possible literals returned by the
/// server (Refer to RFC 3501 Section 4.3 for details).</param>
/// <returns>A response string from the server</returns>
/// <exception cref="IOException">The underlying socket is closed or there was a failure
/// reading from the network.</exception>
string GetResponse(bool resolveLiterals = true) {
const int Newline = 10, CarriageReturn = 13;
using (var mem = new MemoryStream()) {
lock (readLock) {
while (true) {
int i = stream.ReadByte();
if (i == -1)
throw new IOException("The stream could not be read.");
byte b = (byte)i;
if (b == CarriageReturn)
continue;
if (b == Newline) {
string s = Encoding.ASCII.GetString(mem.ToArray());
if (resolveLiterals) {
s = Regex.Replace(s, @"{(\d+)}$", m => {
return "\"" + GetData(Convert.ToInt32(m.Groups[1].Value)) +
"\"" + GetResponse(false);
});
}
ts.TraceInformation("S -> " + s);
return s;
} else
mem.WriteByte(b);
}
}
}
}
/// <summary>
/// Reads the specified amount of bytes from the server. This method blocks until the specified
/// amount of bytes has been read from the network stream.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The read bytes as an ASCII-encoded string.</returns>
/// <exception cref="IOException">The underlying socket is closed or there was a failure
/// reading from the network.</exception>
string GetData(int byteCount) {
byte[] buffer = new byte[4096];
using (var mem = new MemoryStream()) {
lock (readLock) {
while (byteCount > 0) {
int request = byteCount > buffer.Length ? buffer.Length : byteCount;
int read = stream.Read(buffer, 0, request);
mem.Write(buffer, 0, read);
byteCount = byteCount - read;
}
}
string s = Encoding.ASCII.GetString(mem.ToArray());
ts.TraceInformation("S -> " + s);
return s;
}
}
/// <summary>
/// Returns an enumerable collection of capabilities the IMAP server supports. All strings in
/// the returned collection are guaranteed to be upper-case.
/// </summary>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server; The message property of the exception contains the error message returned by
/// the server.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <returns>An enumerable collection of capabilities supported by the server.</returns>
/// <remarks>This method may be called in non-authenticated state.</remarks>
public IEnumerable<string> Capabilities() {
AssertValid(false);
if (capabilities != null)
return capabilities;
lock (sequenceLock) {
if(Authed)
PauseIdling();
string tag = GetTag();
string command = tag + "CAPABILITY";
string response = SendCommandGetResponse(command);
while (response.StartsWith("*")) {
// The server is required to issue an untagged capability response.
if (response.StartsWith("* CAPABILITY ")) {
capabilities = response.Substring(13).Trim().Split(' ')
.Select(s => s.ToUpperInvariant()).ToArray();
}
response = GetResponse();
}
if(Authed)
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
return capabilities;
}
}
/// <summary>
/// Determines whether the specified capability is supported by the server.
/// </summary>
/// <param name="capability">The IMAP capability to probe for (for example "IDLE").</param>
/// <exception cref="ArgumentNullException">The capability parameter is null.</exception>
/// <exception cref="BadServerResponseException">An unexpected response has been received from
/// the server; The message property of the exception contains the error message returned by
/// the server.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <returns>true if the specified capability is supported by the server; Otherwise
/// false.</returns>
/// <remarks>This method may be called in non-authenticated state.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="ctor-2"]/*'/>
public bool Supports(string capability) {
AssertValid(false);
capability.ThrowIfNull("capability");
return (capabilities ?? Capabilities()).Contains(capability,
StringComparer.InvariantCultureIgnoreCase);
}
/// <summary>
/// Changes the name of the specified mailbox.
/// </summary>
/// <param name="mailbox">The mailbox to rename.</param>
/// <param name="newName">The new name the mailbox will be renamed to.</param>
/// <exception cref="ArgumentNullException">The mailbox parameter or the
/// newName parameter is null.</exception>
/// <exception cref="BadServerResponseException">The mailbox could not be renamed; The message
/// property of the exception contains the error message returned by the server.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
public void RenameMailbox(string mailbox, string newName) {
AssertValid();
mailbox.ThrowIfNull("mailbox");
newName.ThrowIfNull("newName");
lock (sequenceLock) {
PauseIdling();
string tag = GetTag();
string response = SendCommandGetResponse(tag + "RENAME " +
Util.UTF7Encode(mailbox).QuoteString() + " " +
Util.UTF7Encode(newName).QuoteString());
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
}
/// <summary>
/// Permanently removes the specified mailbox.
/// </summary>
/// <param name="mailbox">The name of the mailbox to remove.</param>
/// <exception cref="ArgumentNullException">The mailbox parameter is null.</exception>
/// <exception cref="BadServerResponseException">The specified mailbox could not be removed.
/// The message property of the exception contains the error message returned by the
/// server.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
public void DeleteMailbox(string mailbox) {
AssertValid();
mailbox.ThrowIfNull("mailbox");
lock (sequenceLock) {
PauseIdling();
string tag = GetTag();
string response = SendCommandGetResponse(tag + "DELETE " +
Util.UTF7Encode(mailbox).QuoteString());
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
}
/// <summary>
/// Creates a new mailbox with the specified name.
/// </summary>
/// <param name="mailbox">The name of the mailbox to create.</param>
/// <exception cref="ArgumentNullException">The mailbox parameter is null.</exception>
/// <exception cref="BadServerResponseException">The mailbox with the specified name could
/// not be created. The message property of the exception contains the error message returned
/// by the server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
public void CreateMailbox(string mailbox) {
AssertValid();
mailbox.ThrowIfNull("mailbox");
lock (sequenceLock) {
PauseIdling();
string tag = GetTag();
string response = SendCommandGetResponse(tag + "CREATE " +
Util.UTF7Encode(mailbox).QuoteString());
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
}
/// <summary>
/// Selects the specified mailbox so that the messages of the mailbox can be accessed.
/// </summary>
/// <param name="mailbox">The mailbox to select. If this parameter is null, the
/// default mailbox is selected.</param>
/// <exception cref="BadServerResponseException">The specified mailbox could not be selected.
/// The message property of the exception contains the error message returned by the
/// server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <remarks>IMAP Idle must be paused or stopped before calling this method.</remarks>
void SelectMailbox(string mailbox) {
AssertValid();
if (mailbox == null)
mailbox = defaultMailbox;
// The requested mailbox is already selected.
if (selectedMailbox == mailbox)
return;
lock (sequenceLock) {
string tag = GetTag();
string response = SendCommandGetResponse(tag + "SELECT " +
Util.UTF7Encode(mailbox).QuoteString());
while (response.StartsWith("*"))
response = GetResponse();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
selectedMailbox = mailbox;
}
}
/// <summary>
/// Retrieves a list of all available and selectable mailboxes on the server.
/// </summary>
/// <returns>An enumerable collection of the names of all available and selectable
/// mailboxes.</returns>
/// <exception cref="BadServerResponseException">The list of mailboxes could not be retrieved.
/// The message property of the exception contains the error message returned by the
/// server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <remarks>The mailbox name "INBOX" is a special name reserved to mean "the primary mailbox
/// for this user on this server".</remarks>
public IEnumerable<string> ListMailboxes() {
AssertValid();
lock (sequenceLock) {
PauseIdling();
List<string> mailboxes = new List<string>();
string tag = GetTag();
string response = SendCommandGetResponse(tag + "LIST \"\" \"*\"");
while (response.StartsWith("*")) {
Match m = Regex.Match(response, "\\* LIST \\((.*)\\)\\s+\"([^\"]+)\"\\s+(.+)");
if (m.Success) {
string[] attr = m.Groups[1].Value.Split(' ');
bool add = true;
foreach (string a in attr) {
// Only list mailboxes that can actually be selected.
if (a.ToLower() == @"\noselect")
add = false;
}
// Names _should_ be enclosed in double-quotes but not all servers follow through with
// this, so we don't enforce it in the above regex.
string name = Regex.Replace(m.Groups[3].Value, "^\"(.+)\"$", "$1");
try {
name = Util.UTF7Decode(name);
} catch {
// Include the unaltered string in the result if UTF-7 decoding failed for any reason.
}
if (add)
mailboxes.Add(name);
}
response = GetResponse();
}
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
return mailboxes;
}
}
/// <summary>
/// Permanently removes all messages that have the \Deleted flag set from the specified mailbox.
/// </summary>
/// <param name="mailbox">The mailbox to remove all messages from that have the \Deleted flag
/// set. If this parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="BadServerResponseException">The expunge operation could not be completed.
/// The message property of the exception contains the error message returned by the
/// server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <seealso cref="DeleteMessage"/>
public void Expunge(string mailbox = null) {
AssertValid();
lock (sequenceLock) {
PauseIdling();
SelectMailbox(mailbox);
string tag = GetTag();
string response = SendCommandGetResponse(tag + "EXPUNGE");
// The server is required to send an untagged response for each message which is
// deleted before sending OK.
while (response.StartsWith("*"))
response = GetResponse();
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
}
/// <summary>
/// Retrieves status information (total number of messages, various attributes as well as quota
/// information) for the specified mailbox.</summary>
/// <param name="mailbox">The mailbox to retrieve status information for. If this parameter is
/// omitted, the value of the DefaultMailbox property is used to determine the mailbox to
/// operate on.</param>
/// <returns>A MailboxInfo object containing status information for the mailbox.</returns>
/// <exception cref="BadServerResponseException">The operation could not be completed because
/// the server returned an error. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <remarks>Not all IMAP servers support the retrieval of quota information. If it is not
/// possible to retrieve this information, the UsedStorage and FreeStorage properties of the
/// returned MailboxStatus instance are set to 0.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMailboxInfo"]/*'/>
public MailboxInfo GetMailboxInfo(string mailbox = null) {
AssertValid();
// This is not a cheap method to call, it involves a couple of round-trips to the server.
lock (sequenceLock) {
PauseIdling();
if (mailbox == null)
mailbox = defaultMailbox;
MailboxStatus status = GetMailboxStatus(mailbox);
// Collect quota information if the server supports it.
UInt64 used = 0, free = 0;
if (Supports("QUOTA")) {
IEnumerable<MailboxQuota> quotas = GetQuota(mailbox);
foreach (MailboxQuota q in quotas) {
if (q.ResourceName == "STORAGE") {
used = q.Usage;
free = q.Limit - q.Usage;
}
}
}
// Try to collect special-use flags.
IEnumerable<MailboxFlag> flags = GetMailboxFlags(mailbox);
ResumeIdling();
return new MailboxInfo(mailbox, flags, status.Messages, status.Unread, status.NextUID,
used, free);
}
}
/// <summary>
/// Retrieves the set of special-use flags associated with the specified mailbox.
/// </summary>
/// <param name="mailbox">The mailbox to receive the special-use flags for. If this parameter is
/// omitted, the value of the DefaultMailbox property is used to determine the mailbox to
/// operate on.</param>
/// <exception cref="BadServerResponseException">The operation could not be completed because
/// the server returned an error. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <returns>An enumerable collection of special-use flags set on the specified
/// mailbox.</returns>
/// <remarks>This feature is an optional extension to the IMAP protocol and as such some servers
/// may not report any flags at all.</remarks>
IEnumerable<MailboxFlag> GetMailboxFlags(string mailbox = null) {
Dictionary<string, MailboxFlag> dictFlags =
new Dictionary<string, MailboxFlag>(StringComparer.OrdinalIgnoreCase) {
{ @"\All", MailboxFlag.AllMail }, { @"\AllMail", MailboxFlag.AllMail },
{ @"\Archive", MailboxFlag.Archive }, { @"\Drafts", MailboxFlag.Drafts },
{ @"\Junk", MailboxFlag.Spam }, { @"\Spam", MailboxFlag.Spam },
{ @"\Trash", MailboxFlag.Trash }, { @"\Rubbish", MailboxFlag.Trash },
{ @"\Sent", MailboxFlag.Sent }, { @"\SentItems", MailboxFlag.Sent }
};
List<MailboxFlag> list = new List<MailboxFlag>();
AssertValid();
lock (sequenceLock) {
PauseIdling();
if (mailbox == null)
mailbox = defaultMailbox;
string tag = GetTag();
// Use XLIST if server supports it, otherwise at least try LIST and hope server implements
// the "LIST Extension for Special-Use Mailboxes" (Refer to RFC6154).
string command = Supports("XLIST") ? "XLIST" : "LIST";
string response = SendCommandGetResponse(tag + command + " \"\" " +
Util.UTF7Encode(mailbox).QuoteString());
while (response.StartsWith("*")) {
Match m = Regex.Match(response, "\\* X?LIST \\((.*)\\)\\s+\"([^\"]+)\"\\s+(.+)");
if (m.Success) {
string[] flags = m.Groups[1].Value.Split(' ');
foreach (string f in flags) {
if (dictFlags.ContainsKey(f))
list.Add(dictFlags[f]);
}
}
response = GetResponse();
}
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
return list;
}
/// <summary>
/// Retrieves status information (total number of messages, number of unread messages, etc.) for
/// the specified mailbox.</summary>
/// <param name="mailbox">The mailbox to retrieve status information for. If this parameter is
/// omitted, the value of the DefaultMailbox property is used to determine the mailbox to
/// operate on.</param>
/// <returns>A MailboxStatus object containing status information for the mailbox.</returns>
/// <exception cref="BadServerResponseException">The operation could not be completed because
/// the server returned an error. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
MailboxStatus GetMailboxStatus(string mailbox = null) {
AssertValid();
int messages = 0, unread = 0;
uint uid = 0;
lock (sequenceLock) {
PauseIdling();
if (mailbox == null)
mailbox = defaultMailbox;
string tag = GetTag();
string response = SendCommandGetResponse(tag + "STATUS " +
Util.UTF7Encode(mailbox).QuoteString() + " (MESSAGES UNSEEN UIDNEXT)");
while (response.StartsWith("*")) {
Match m = Regex.Match(response, @"\* STATUS.*MESSAGES (\d+)");
if (m.Success)
messages = Convert.ToInt32(m.Groups[1].Value);
m = Regex.Match(response, @"\* STATUS.*UNSEEN (\d+)");
if (m.Success)
unread = Convert.ToInt32(m.Groups[1].Value);
m = Regex.Match(response, @"\* STATUS.*UIDNEXT (\d+)");
if (m.Success)
uid = Convert.ToUInt32(m.Groups[1].Value);
response = GetResponse();
}
ResumeIdling();
if (!IsResponseOK(response, tag))
throw new BadServerResponseException(response);
}
return new MailboxStatus(messages, unread, uid);
}
/// <summary>
/// Searches the specified mailbox for messages that match the given search criteria.
/// </summary>
/// <param name="criteria">A search criteria expression; Only messages that match this
/// expression will be included in the result set returned by this method.</param>
/// <param name="mailbox">The mailbox that will be searched. If this parameter is omitted, the
/// value of the DefaultMailbox property is used to determine the mailbox to operate on.</param>
/// <exception cref="ArgumentNullException">The criteria parameter is null.</exception>
/// <exception cref="BadServerResponseException">The search could not be completed. The message
/// property of the exception contains the error message returned by the server.</exception>
/// <exception cref="ObjectDisposedException">The ImapClient object has been disposed.</exception>
/// <exception cref="IOException">There was a failure writing to or reading from the
/// network.</exception>
/// <exception cref="NotAuthenticatedException">The method was called in non-authenticated
/// state, i.e. before logging in.</exception>
/// <exception cref="NotSupportedException">The search values contain characters beyond the
/// ASCII range and the server does not support handling non-ASCII strings.</exception>
/// <returns>An enumerable collection of unique identifiers (UIDs) which can be used with the
/// GetMessage family of methods to download the mail messages.</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each message which uniquely
/// identifies the message within the respective mailbox. No two messages in a mailbox share
/// the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Search"]/*'/>
public IEnumerable<uint> Search(SearchCondition criteria, string mailbox = null) {
AssertValid();
criteria.ThrowIfNull("criteria");
lock (sequenceLock) {
PauseIdling();
SelectMailbox(mailbox);
string tag = GetTag(), str = criteria.ToString();
StringReader reader = new StringReader(str);
bool useUTF8 = str.Contains("\r\n");