forked from andyedinborough/aenetmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImapClient.cs
960 lines (808 loc) · 33.9 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
using AE.Net.Mail.Imap;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AE.Net.Mail
{
public enum AuthMethods
{
Login,
CRAMMD5,
SaslOAuth
}
public class ImapClient : TextClient, IMailClient
{
private string _SelectedMailbox;
private Mailbox _Mailbox;
private int _tag = 0;
private string[] _Capability;
private bool _Idling;
private Task _IdleTask;
private Task _ResponseTask;
private readonly ModifiedUtf7Encoding _utf7 = new ModifiedUtf7Encoding();
private string _FetchHeaders = null;
public ImapClient()
{
IdleTimeout = 1200000;
}
public ImapClient(string host, string username, string password, AuthMethods method = AuthMethods.Login, int port = 143, bool secure = false, bool skipSslValidation = false)
: this()
{
Connect(host, port, secure, skipSslValidation);
AuthMethod = method;
Login(username, password);
}
public int IdleTimeout { get; set; }
public virtual AuthMethods AuthMethod { get; set; }
public Mailbox Mailbox
{
get
{
CheckMailboxSelected();
return _Mailbox;
}
}
private string GetTag()
{
_tag++;
return string.Format("xm{0:000} ", _tag);
}
public virtual bool Supports(string command)
{
return (_Capability ?? Capability()).Contains(command, StringComparer.OrdinalIgnoreCase);
}
private EventHandler<MessageEventArgs> _NewMessage;
public virtual event EventHandler<MessageEventArgs> NewMessage
{
add
{
_NewMessage += value;
IdleStart();
}
remove
{
_NewMessage -= value;
if (!HasEvents)
{
IdleStop();
}
}
}
private EventHandler<MessageEventArgs> _MessageDeleted;
public virtual event EventHandler<MessageEventArgs> MessageDeleted
{
add
{
_MessageDeleted += value;
IdleStart();
}
remove
{
_MessageDeleted -= value;
if (!HasEvents)
{
IdleStop();
}
}
}
public event EventHandler<ImapClientExceptionEventArgs> ImapException;
protected virtual void IdleStart()
{
CheckMailboxSelected();
_Idling = true;
if (!Supports("IDLE"))
{
throw new InvalidOperationException("This IMAP server does not support the IDLE command");
}
IdleResume();
}
protected virtual void IdlePause()
{
if (_IdleTask == null || !_Idling)
return;
CheckConnectionStatus();
SendCommand("DONE");
if (!_IdleTask.Wait(ServerTimeout))
{
//Not responding
Disconnect();
ImapClientException e = new ImapClientException("Lost communication to IMAP server, connection closed.");
ImapClientExceptionEventArgs args = new ImapClientExceptionEventArgs(e);
Task.Factory.StartNew(() => ImapException.Fire(this, args));
}
_IdleTask.Dispose();
_IdleTask = null;
}
protected virtual void IdleResume()
{
if (!_Idling)
return;
IdleResumeCommand();
if (_IdleTask == null)
{
_IdleTask = new Task(() => WatchIdleQueue());
_IdleTask.Start();
}
}
private void IdleResumeCommand()
{
SendCommandGetResponse(GetTag() + "IDLE");
}
private bool HasEvents => _MessageDeleted != null || _NewMessage != null;
protected virtual void IdleStop()
{
IdlePause();
_Idling = false;
}
public virtual bool TryGetResponse(out string response)
{
string resp = response = null;
_ResponseTask = Task.Factory.StartNew(() =>
{
resp = GetResponse(IdleTimeout + ServerTimeout * 3);
});
try
{
if (_ResponseTask.Wait(IdleTimeout))
{
response = resp;
_ResponseTask.Dispose();
_ResponseTask = null;
return true;
}
else
return false;
}
catch (AggregateException)
{
throw;
}
}
private void WatchIdleQueue()
{
try
{
string last = null;
while (true)
{
if (!TryGetResponse(out string resp))
{
//Child task should still running on ReadByte here.
//Need to send some data to get it to exit.
SendCommand("DONE"); //_ResponseTask should pick up response and exit
if (!_ResponseTask.Wait(ServerTimeout))
{
//Not responding
Disconnect();
throw new ImapClientException("Lost communication to IMAP server, connection closed.");
}
_ResponseTask.Dispose();
_ResponseTask = null;
IdleResumeCommand();
continue;
}
if (resp.Contains("OK IDLE")) //Server response after DONE
return;
var data = resp.Split(' ');
if (data[0] == "*" && data.Length >= 3)
{
var e = new MessageEventArgs { Client = this, MessageCount = int.Parse(data[1]) };
if (data[2].Is("EXISTS") && !last.Is("EXPUNGE") && e.MessageCount > 0)
{
Task.Factory.StartNew(() => _NewMessage.Fire(this, e)); //Fire the event in a task
}
else if (data[2].Is("EXPUNGE"))
{
Task.Factory.StartNew(() => _MessageDeleted.Fire(this, e));
}
last = data[2];
}
}
}
catch (Exception e)
{
ImapClientExceptionEventArgs args = new ImapClientExceptionEventArgs(e);
Task.Factory.StartNew(() => ImapException.Fire(this, args));
}
}
public virtual void AppendMail(MailMessage email, string mailbox = null)
{
var body = new StringBuilder();
using (var txt = new System.IO.StringWriter(body))
email.Save(txt);
AppendMail(body.ToString(), email.RawFlags.Length > 0 ? email.Flags : (Flags?)null, mailbox);
}
public virtual void AppendMail(string rawMessage, Flags? messageFlags = null, string mailbox = null)
{
IdlePause();
mailbox = _utf7.Encode(mailbox);
string flags = string.Empty;
string size = rawMessage.Length.ToString();
if (messageFlags.HasValue)
{
flags = " (" + string.Join(" ", messageFlags.Value) + ")";
}
if (mailbox == null)
CheckMailboxSelected();
mailbox ??= _SelectedMailbox;
string body = rawMessage;
string command = GetTag() + "APPEND " + (mailbox ?? _SelectedMailbox).QuoteString() + flags + " {" + size + "}";
string response = SendCommandGetResponse(command);
if (response.StartsWith("+"))
{
_ = SendCommandGetResponse(body.ToString());
}
IdleResume();
}
public virtual void Noop()
{
IdlePause();
var tag = GetTag();
var response = SendCommandGetResponse(tag + "NOOP");
while (!response.StartsWith(tag))
{
response = GetResponse();
}
IdleResume();
}
public virtual string[] Capability()
{
IdlePause();
string command = GetTag() + "CAPABILITY";
_ = SendCommandGetResponse(command);
IdleResume();
return _Capability;
}
public virtual void Copy(string messageset, string destination)
{
CheckMailboxSelected();
IdlePause();
string prefix = null;
if (messageset.StartsWith("UID ", StringComparison.OrdinalIgnoreCase))
{
messageset = messageset[4..];
prefix = "UID ";
}
string command = string.Concat(GetTag(), prefix, "COPY ", messageset, " " + destination.QuoteString());
SendCommandCheckOK(command);
IdleResume();
}
public virtual void CreateMailbox(string mailbox)
{
IdlePause();
string command = GetTag() + "CREATE " + _utf7.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual void DeleteMailbox(string mailbox)
{
IdlePause();
string command = GetTag() + "DELETE " + _utf7.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual Mailbox Examine(string mailboxName)
{
IdlePause();
Mailbox mailbox = mailboxName.Equals(_SelectedMailbox) ? _Mailbox : new Mailbox(mailboxName);
string tag = GetTag();
string command = tag + "EXAMINE " + _utf7.Encode(mailboxName).QuoteString();
_ = SendCommandGetResponse(command, mailbox);
IdleResume();
return mailbox;
}
public virtual void Expunge()
{
CheckMailboxSelected();
IdlePause();
string tag = GetTag();
string command = tag + "EXPUNGE";
_ = SendCommandGetResponse(command);
IdleResume();
}
public virtual void DeleteMessage(MailMessage msg)
{
DeleteMessage(msg.Uid);
}
public virtual void DeleteMessage(string uid)
{
CheckMailboxSelected();
Store("UID " + uid, true, "\\Seen \\Deleted");
}
public virtual void MoveMessage(string uid, string folderName)
{
CheckMailboxSelected();
Copy("UID " + uid, folderName);
DeleteMessage(uid);
}
protected virtual void CheckMailboxSelected()
{
if (string.IsNullOrEmpty(_SelectedMailbox))
{
SelectMailbox("INBOX");
}
}
public virtual MailMessage GetMessage(string uid, bool headersonly = false)
{
return GetMessage(uid, headersonly, true);
}
public virtual MailMessage GetMessage(int index, bool headersonly = false)
{
return GetMessage(index, headersonly, true);
}
public virtual MailMessage GetMessage(int index, bool headersonly, bool setseen)
{
return GetMessages(index, index, headersonly, setseen).FirstOrDefault();
}
public virtual MailMessage GetMessage(string uid, bool headersonly, bool setseen)
{
return GetMessages(uid, uid, headersonly, setseen).FirstOrDefault();
}
public virtual MailMessage[] GetMessages(string startUID, string endUID, bool headersonly = true, bool setseen = false)
{
return GetMessages(startUID, endUID, true, headersonly, setseen);
}
public virtual MailMessage[] GetMessages(int startIndex, int endIndex, bool headersonly = true, bool setseen = false)
{
return GetMessages((startIndex + 1).ToString(), (endIndex + 1).ToString(), false, headersonly, setseen);
}
public virtual void DownloadMessage(System.IO.Stream stream, int index, bool setseen)
{
GetMessages((index + 1).ToString(), (index + 1).ToString(), false, false, false, setseen, (message, size, headers) =>
{
Utilities.CopyStream(message, stream, size);
return null;
});
}
public virtual void DownloadMessage(System.IO.Stream stream, string uid, bool setseen)
{
GetMessages(uid, uid, true, false, false, setseen, (message, size, headers) =>
{
Utilities.CopyStream(message, stream, size);
return null;
});
}
public virtual MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
{
var x = new List<MailMessage>();
GetMessages(start, end, uid, false, headersonly, setseen, (stream, size, imapHeaders) =>
{
var mail = new MailMessage { Encoding = Encoding };
mail.Size = size;
if (imapHeaders["UID"] != null)
mail.Uid = imapHeaders["UID"];
if (imapHeaders["Flags"] != null)
mail.SetFlags(imapHeaders["Flags"]);
mail.Load(_Stream, headersonly, mail.Size);
foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
x.Add(mail);
return mail;
});
return x.ToArray();
}
public virtual void GetMessages(string start, string end, bool uid, bool uidsonly, bool headersonly, bool setseen, Action<MailMessage> processCallback)
{
GetMessages(start, end, uid, uidsonly, headersonly, setseen, (stream, size, imapHeaders) =>
{
var mail = new MailMessage { Encoding = Encoding };
mail.Size = size;
if (imapHeaders["UID"] != null)
mail.Uid = imapHeaders["UID"];
if (imapHeaders["Flags"] != null)
mail.SetFlags(imapHeaders["Flags"]);
mail.Load(_Stream, headersonly, mail.Size);
foreach (var key in imapHeaders.AllKeys.Except(new[] { "UID", "Flags", "BODY[]", "BODY[HEADER]" }, StringComparer.OrdinalIgnoreCase))
mail.Headers.Add(key, new HeaderValue(imapHeaders[key]));
processCallback(mail);
return mail;
});
}
public virtual void GetMessages(string start, string end, bool uid, bool uidsonly, bool headersonly, bool setseen, Func<System.IO.Stream, int, NameValueCollection, MailMessage> action)
{
CheckMailboxSelected();
IdlePause();
string tag = GetTag();
string command = tag + (uid ? "UID " : null)
+ "FETCH " + start + ":" + end + " ("
+ _FetchHeaders + "UID FLAGS"
+ (uidsonly ? null : (setseen ? " BODY[" : " BODY.PEEK[") + (headersonly ? "HEADER]" : "]"))
+ ")";
string response;
SendCommand(command);
while (true)
{
response = GetResponse();
if (string.IsNullOrEmpty(response) || response.Contains(tag + "OK"))
break;
if (response[0] != '*' || !response.Contains("FETCH ("))
continue;
var imapHeaders = Utilities.ParseImapHeader(response[(response.IndexOf('(') + 1)..]);
string body = (imapHeaders["BODY[HEADER]"] ?? imapHeaders["BODY[]"]);
if (body == null && !uidsonly)
{
RaiseWarning(null, "Expected BODY[] in stream, but received \"" + response + "\"");
break;
}
var size = (uidsonly ? 0 : body.Trim('{', '}').ToInt());
var msg = action(_Stream, size, imapHeaders);
// with only uids we have no body and the closing bracket is on the same line
if (!uidsonly)
{
response = GetResponse();
if (response == null)
{
RaiseWarning(null, "Expected \")\" in stream, but received nothing");
break;
}
}
var n = response.Trim().LastOrDefault();
if (n != ')')
{
RaiseWarning(null, "Expected \")\" in stream, but received \"" + response + "\"");
}
}
IdleResume();
}
public virtual Quota GetQuota(string mailbox)
{
if (!Supports("NAMESPACE"))
throw new Exception("This command is not supported by the server!");
IdlePause();
Quota quota = null;
string command = GetTag() + "GETQUOTAROOT " + _utf7.Encode(mailbox).QuoteString();
string response = SendCommandGetResponse(command);
string reg = "\\* QUOTA (.*?) \\((.*?) (.*?) (.*?)\\)";
while (response.StartsWith("*"))
{
Match m = Regex.Match(response, reg);
if (m.Groups.Count > 1)
{
quota = new Quota(m.Groups[1].ToString(),
m.Groups[2].ToString(),
int.Parse(m.Groups[3].ToString()),
int.Parse(m.Groups[4].ToString())
);
break;
}
response = GetResponse();
}
IdleResume();
return quota;
}
public virtual Mailbox[] ListMailboxes(string reference, string pattern)
{
IdlePause();
var x = new List<Mailbox>();
string command = GetTag() + "LIST " + reference.QuoteString() + " " + pattern.QuoteString();
const string reg = "\\* LIST \\(([^\\)]*)\\) \\\"([^\\\"]+)\\\" \\\"?([^\\\"]+)\\\"?";
string response = SendCommandGetResponse(command);
Match m = Regex.Match(response, reg);
while (m.Groups.Count > 1)
{
Mailbox mailbox = new Mailbox(ModifiedUtf7Encoding.Decode(m.Groups[3].Value));
mailbox.SetFlags(m.Groups[1].Value);
x.Add(mailbox);
response = GetResponse();
m = Regex.Match(response, reg);
}
IdleResume();
return x.ToArray();
}
public virtual Mailbox[] ListSuscribesMailboxes(string reference, string pattern)
{
IdlePause();
var x = new List<Mailbox>();
string command = GetTag() + "LSUB " + reference.QuoteString() + " " + pattern.QuoteString();
string reg = "\\* LSUB \\(([^\\)]*)\\) \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\"";
string response = SendCommandGetResponse(command);
Match m = Regex.Match(response, reg);
while (m.Groups.Count > 1)
{
Mailbox mailbox = new Mailbox(ModifiedUtf7Encoding.Decode(m.Groups[3].Value));
x.Add(mailbox);
response = GetResponse();
m = Regex.Match(response, reg);
}
IdleResume();
return x.ToArray();
}
internal override void OnLogin(string login, string password)
{
string command = string.Empty;
string result = string.Empty;
string tag = GetTag();
string key;
switch (AuthMethod)
{
case AuthMethods.CRAMMD5:
command = tag + "AUTHENTICATE CRAM-MD5";
result = SendCommandGetResponse(command);
// retrieve server key
key = result.Replace("+ ", "");
key = Encoding.Default.GetString(Convert.FromBase64String(key));
// calcul hash
using (var kMd5 = new HMACMD5(Encoding.ASCII.GetBytes(password)))
{
byte[] hash1 = kMd5.ComputeHash(Encoding.ASCII.GetBytes(key));
key = BitConverter.ToString(hash1).ToLower().Replace("-", "");
result = Convert.ToBase64String(Encoding.ASCII.GetBytes(login + " " + key));
result = SendCommandGetResponse(result);
}
break;
case AuthMethods.Login:
command = tag + "LOGIN " + login.QuoteString() + " " + password.QuoteString();
result = SendCommandGetResponse(command);
break;
case AuthMethods.SaslOAuth:
string sasl = "user=" + login + "\x01" + "auth=Bearer " + password + "\x01" + "\x01";
string base64 = Convert.ToBase64String(Encoding.GetBytes(sasl));
command = tag + "AUTHENTICATE XOAUTH2 " + base64;
result = SendCommandGetResponse(command);
break;
default:
throw new NotSupportedException();
}
if (!IsResultOK(result))
{
if (result.StartsWith("+ ") && result.EndsWith("=="))
{
string jsonErr = Utilities.DecodeBase64(result[2..], Encoding.UTF7);
throw new Exception(jsonErr);
}
else
throw new Exception(result);
}
//if (Supports("COMPRESS=DEFLATE")) {
// SendCommandCheckOK(GetTag() + "compress deflate");
// _Stream0 = _Stream;
// // _Reader = new System.IO.StreamReader(new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Decompress, true), System.Text.Encoding.Default);
// // _Stream = new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Compress, true);
//}
if (Supports("X-GM-EXT-1"))
{
_FetchHeaders = "X-GM-MSGID X-GM-THRID X-GM-LABELS ";
}
}
internal override void OnLogout()
{
if (IsConnected)
{
if (_IdleTask != null && _Idling)
{
IdleStop();
}
SendCommand(GetTag() + "LOGOUT");
}
}
public virtual Namespaces Namespace()
{
if (!Supports("NAMESPACE"))
throw new NotSupportedException("This command is not supported by the server!");
IdlePause();
string command = GetTag() + "NAMESPACE";
string response = SendCommandGetResponse(command);
if (!response.StartsWith("* NAMESPACE"))
{
throw new Exception("Unknow server response !");
}
response = response[12..];
Namespaces n = new Namespaces();
//[TODO] be sure to parse correctly namespace when not all namespaces are present. NIL character
string reg = @"\((.*?)\) \((.*?)\) \((.*?)\)$";
Match m = Regex.Match(response, reg);
if (m.Groups.Count != 4)
throw new Exception("En error occure, this command is not fully supported !");
string reg2 = "\\(\\\"(.*?)\\\" \\\"(.*?)\\\"\\)";
Match m2 = Regex.Match(m.Groups[1].ToString(), reg2);
while (m2.Groups.Count > 1)
{
n.ServerNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
m2 = Regex.Match(m.Groups[2].ToString(), reg2);
while (m2.Groups.Count > 1)
{
n.UserNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
m2 = Regex.Match(m.Groups[3].ToString(), reg2);
while (m2.Groups.Count > 1)
{
n.SharedNamespace.Add(new Namespace(m2.Groups[1].Value, m2.Groups[2].Value));
m2 = m2.NextMatch();
}
GetResponse();
IdleResume();
return n;
}
public virtual int GetMessageCount()
{
CheckMailboxSelected();
return GetMessageCount(null);
}
public virtual int GetMessageCount(string mailbox)
{
IdlePause();
string command = GetTag() + "STATUS " + Utilities.QuoteString(_utf7.Encode(mailbox) ?? _SelectedMailbox) + " (MESSAGES)";
string response = SendCommandGetResponse(command);
string reg = @"\* STATUS.*MESSAGES (\d+)";
int result = 0;
while (response.StartsWith("*"))
{
Match m = Regex.Match(response, reg);
if (m.Groups.Count > 1)
result = Convert.ToInt32(m.Groups[1].ToString());
response = GetResponse();
_ = Regex.Match(response, reg);
}
IdleResume();
return result;
}
public virtual void RenameMailbox(string frommailbox, string tomailbox)
{
IdlePause();
string command = GetTag() + "RENAME " + frommailbox.QuoteString() + " " + tomailbox.QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual string[] Search(SearchCondition criteria, bool uid = true)
{
return Search(criteria.ToString(), uid);
}
public virtual string[] Search(string criteria, bool uid = true)
{
CheckMailboxSelected();
string isuid = uid ? "UID " : "";
string tag = GetTag();
string command = tag + isuid + "SEARCH " + criteria;
string response = SendCommandGetResponse(command);
if (!response.StartsWith("* SEARCH", StringComparison.InvariantCultureIgnoreCase) && !IsResultOK(response))
{
throw new Exception(response);
}
string temp;
while (!(temp = GetResponse()).StartsWith(tag))
{
response += Environment.NewLine + temp;
}
var m = Regex.Match(response, @"^\* SEARCH (.*)", RegexOptions.Multiline);
return m.Groups[1].Value.Trim().Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToArray();
}
public virtual Lazy<MailMessage>[] SearchMessages(SearchCondition criteria, bool headersonly = false, bool setseen = false)
{
return Search(criteria, true)
.Select(x => new Lazy<MailMessage>(() => GetMessage(x, headersonly, setseen)))
.ToArray();
}
public virtual Mailbox SelectMailbox(string mailboxName)
{
IdlePause();
var tag = GetTag();
var command = tag + "SELECT " + _utf7.Encode(mailboxName).QuoteString();
_Mailbox = new Mailbox(mailboxName);
_SelectedMailbox = mailboxName;
var response = SendCommandGetResponse(command);
CheckResultOK(response);
_Mailbox.IsWritable = Regex.IsMatch(response, "READ.WRITE", RegexOptions.IgnoreCase);
IdleResume();
return _Mailbox;
}
protected override string SendCommandGetResponse(string command)
{
return SendCommandGetResponse(command, _Mailbox);
}
protected virtual string SendCommandGetResponse(string command, Mailbox mailbox)
{
var response = base.SendCommandGetResponse(command);
response = HandleUntaggedResponse(response, Mailbox);
return response;
}
protected virtual string HandleUntaggedResponse(string response, Mailbox mailbox)
{
Match match;
while (response.StartsWith("*"))
{
if (mailbox != null)
{
if ((match = Regex.Match(response, @"\d+(?=\s+EXISTS)")).Success)
mailbox.NumMsg = match.Value.ToInt();
else if ((match = Regex.Match(response, @"\d+(?=\s+RECENT)")).Success)
mailbox.NumNewMsg = match.Value.ToInt();
else if ((match = Regex.Match(response, @"(?<=UNSEEN\s+)\d+")).Success)
mailbox.NumUnSeen = match.Value.ToInt();
else if ((match = Regex.Match(response, @"(?<=\sFLAGS\s+\().*?(?=\))")).Success)
mailbox.SetFlags(match.Value);
else if ((match = Regex.Match(response, @"UIDVALIDITY (\d+)")).Success)
mailbox.UIDValidity = match.Groups[1].Value.ToInt();
else if (response.StartsWith("* CAPABILITY "))
{
response = response[13..];
_Capability = response.Trim().Split(' ');
}
else if (response.StartsWith("* OK"))
{
}
else return response;
}
response = GetResponse();
}
return response;
}
public virtual void SetFlags(Flags flags, params MailMessage[] msgs)
{
SetFlags(FlagsToFlagString(flags), msgs);
}
public virtual void SetFlags(string flags, params MailMessage[] msgs)
{
Store("UID " + string.Join(" ", msgs.Select(x => x.Uid)), true, flags);
foreach (var msg in msgs)
{
msg.SetFlags(flags);
}
}
private static string FlagsToFlagString(Flags flags)
{
return string.Join(" ", flags.ToString().Split(',').Select(x => "\\" + x.Trim()));
}
public virtual void AddFlags(Flags flags, params MailMessage[] msgs)
{
AddFlags(FlagsToFlagString(flags), msgs);
}
public virtual void AddFlags(string flags, params MailMessage[] msgs)
{
Store("UID " + string.Join(" ", msgs.Select(x => x.Uid)), false, flags);
foreach (var msg in msgs)
{
msg.SetFlags(FlagsToFlagString(msg.Flags) + " " + flags);
}
}
public virtual void Store(string messageset, bool replace, string flags)
{
CheckMailboxSelected();
IdlePause();
string prefix = null;
if (messageset.StartsWith("UID ", StringComparison.OrdinalIgnoreCase))
{
messageset = messageset[4..];
prefix = "UID ";
}
string command = string.Concat(GetTag(), prefix, "STORE ", messageset, " ", replace ? "" : "+", "FLAGS.SILENT (" + flags + ")");
string response = SendCommandGetResponse(command);
CheckResultOK(response);
IdleResume();
}
public virtual void SuscribeMailbox(string mailbox)
{
IdlePause();
string command = GetTag() + "SUBSCRIBE " + _utf7.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
public virtual void UnSuscribeMailbox(string mailbox)
{
IdlePause();
string command = GetTag() + "UNSUBSCRIBE " + _utf7.Encode(mailbox).QuoteString();
SendCommandCheckOK(command);
IdleResume();
}
internal override void CheckResultOK(string response)
{
if (!IsResultOK(response))
{
response = response[response.IndexOf(" ")..].Trim();
throw new Exception(response);
}
}
internal static bool IsResultOK(string response)
{
response = response[response.IndexOf(" ")..].Trim();
return response.ToUpper().StartsWith("OK");
}
}
}