-
-
Notifications
You must be signed in to change notification settings - Fork 808
/
SmtpClient.cs
1992 lines (1721 loc) · 70.2 KB
/
SmtpClient.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
//
// SmtpClient.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using MimeKit;
using MimeKit.IO;
using System.Threading.Tasks;
#if NETFX_CORE
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Socket = Windows.Networking.Sockets.StreamSocket;
using Encoding = Portable.Text.Encoding;
#else
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
#endif
using MailKit.Security;
namespace MailKit.Net.Smtp {
/// <summary>
/// An SMTP client that can be used to send email messages.
/// </summary>
/// <remarks>
/// <para>The <see cref="SmtpClient"/> class supports both the "smtp" and "smtps" protocols. The "smtp"
/// protocol makes a clear-text connection to the SMTP server and does not use SSL or TLS unless the SMTP
/// server supports the <a href="https://tools.ietf.org/html/rfc3207">STARTTLS</a> extension. The "smtps"
/// protocol, however, connects to the SMTP server using an SSL-wrapped connection.</para>
/// <para>The connection established by any of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a> methods may be re-used if an
/// application wishes to send multiple messages to the same SMTP server. Since connecting and authenticating
/// can be expensive operations, re-using a connection can significantly improve performance when sending a
/// large number of messages to the same SMTP server over a short period of time.</para>
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessages" />
/// </example>
public class SmtpClient : MailTransport
{
static readonly byte[] EndData = Encoding.ASCII.GetBytes ("\r\n.\r\n");
const int MaxLineLength = 998;
enum SmtpCommand {
MailFrom,
RcptTo
}
readonly HashSet<string> authenticationMechanisms = new HashSet<string> ();
readonly List<SmtpCommand> queued = new List<SmtpCommand> ();
SmtpCapabilities capabilities;
int timeout = 100000;
bool authenticated;
bool connected;
bool disposed;
bool secure;
string host;
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpClient"/> class.
/// </summary>
/// <remarks>
/// Before you can send messages with the <see cref="SmtpClient"/>, you must first call one of
/// the <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a> methods.
/// Depending on whether the SMTP server requires authenticating or not, you may also need to
/// authenticate using one of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Authenticate.htm">Authenticate</a> methods.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessages" />
/// </example>
public SmtpClient () : this (new NullProtocolLogger ())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpClient"/> class.
/// </summary>
/// <remarks>
/// Before you can send messages with the <see cref="SmtpClient"/>, you must first call one of
/// the <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a> methods.
/// Depending on whether the SMTP server requires authenticating or not, you may also need to
/// authenticate using one of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Authenticate.htm">Authenticate</a> methods.
/// </remarks>
/// <param name="protocolLogger">The protocol logger.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="protocolLogger"/> is <c>null</c>.
/// </exception>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="ProtocolLogger"/>
/// </example>
public SmtpClient (IProtocolLogger protocolLogger) : base (protocolLogger)
{
}
/// <summary>
/// Get the underlying SMTP stream.
/// </summary>
/// <remarks>
/// Gets the underlying SMTP stream.
/// </remarks>
/// <value>The SMTP stream.</value>
SmtpStream Stream {
get; set;
}
/// <summary>
/// Gets an object that can be used to synchronize access to the SMTP server.
/// </summary>
/// <remarks>
/// <para>Gets an object that can be used to synchronize access to the SMTP server.</para>
/// <para>When using the non-Async methods from multiple threads, it is important to lock the
/// <see cref="SyncRoot"/> object for thread safety when using the synchronous methods.</para>
/// </remarks>
/// <value>The lock object.</value>
public override object SyncRoot {
get { return this; }
}
/// <summary>
/// Get the protocol supported by the message service.
/// </summary>
/// <remarks>
/// Gets the protocol supported by the message service.
/// </remarks>
/// <value>The protocol.</value>
protected override string Protocol {
get { return "smtp"; }
}
/// <summary>
/// Get the capabilities supported by the SMTP server.
/// </summary>
/// <remarks>
/// The capabilities will not be known until a successful connection has been made
/// and may change once the client is authenticated.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="Capabilities"/>
/// </example>
/// <value>The capabilities.</value>
/// <exception cref="System.ArgumentException">
/// Capabilities cannot be enabled, they may only be disabled.
/// </exception>
public SmtpCapabilities Capabilities {
get { return capabilities; }
set {
if ((capabilities | value) > capabilities)
throw new ArgumentException ("Capabilities cannot be enabled, they may only be disabled.", "value");
capabilities = value;
}
}
/// <summary>
/// Gets or sets the local domain.
/// </summary>
/// <remarks>
/// The local domain is used in the HELO or EHLO commands sent to
/// the SMTP server. If left unset, the local IP address will be
/// used instead.
/// </remarks>
/// <value>The local domain.</value>
public string LocalDomain {
get; set;
}
/// <summary>
/// Get the maximum message size supported by the server.
/// </summary>
/// <remarks>
/// <para>The maximum message size will not be known until a successful connection has
/// been made and may change once the client is authenticated.</para>
/// <note type="note">This value is only relevant if the <see cref="Capabilities"/> includes
/// the <see cref="SmtpCapabilities.Size"/> flag.</note>
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="Capabilities"/>
/// </example>
/// <value>The maximum message size supported by the server.</value>
public uint MaxSize {
get; private set;
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException ("SmtpClient");
}
#region IMailService implementation
/// <summary>
/// Get the authentication mechanisms supported by the SMTP server.
/// </summary>
/// <remarks>
/// <para>The authentication mechanisms are queried as part of the connection
/// process.</para>
/// <note type="tip">To prevent the usage of certain authentication mechanisms,
/// simply remove them from the <see cref="AuthenticationMechanisms"/> hash set
/// before authenticating.</note>
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="Capabilities"/>
/// </example>
/// <value>The authentication mechanisms.</value>
public override HashSet<string> AuthenticationMechanisms {
get { return authenticationMechanisms; }
}
/// <summary>
/// Get or set the timeout for network streaming operations, in milliseconds.
/// </summary>
/// <remarks>
/// Gets or sets the underlying socket stream's <see cref="System.IO.Stream.ReadTimeout"/>
/// and <see cref="System.IO.Stream.WriteTimeout"/> values.
/// </remarks>
/// <value>The timeout in milliseconds.</value>
public override int Timeout {
get { return timeout; }
set {
if (IsConnected && Stream.CanTimeout) {
Stream.WriteTimeout = value;
Stream.ReadTimeout = value;
}
timeout = value;
}
}
/// <summary>
/// Get whether or not the client is currently connected to an SMTP server.
/// </summary>
/// <remarks>
/// When a <see cref="SmtpProtocolException"/> is caught, the connection state of the
/// <see cref="SmtpClient"/> should be checked before continuing.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="ExceptionHandling"/>
/// </example>
/// <value><c>true</c> if the client is connected; otherwise, <c>false</c>.</value>
public override bool IsConnected {
get { return connected; }
}
/// <summary>
/// Get whether or not the connection is secure (typically via SSL or TLS).
/// </summary>
/// <remarks>
/// Gets whether or not the connection is secure (typically via SSL or TLS).
/// </remarks>
/// <value><c>true</c> if the connection is secure; otherwise, <c>false</c>.</value>
public override bool IsSecure {
get { return IsConnected && secure; }
}
/// <summary>
/// Get whether or not the client is currently authenticated with the SMTP server.
/// </summary>
/// <remarks>
/// <para>Gets whether or not the client is currently authenticated with the SMTP server.</para>
/// <para>To authenticate with the SMTP server, use one of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Authenticate.htm">Authenticate</a>
/// methods.</para>
/// </remarks>
/// <value><c>true</c> if the client is connected; otherwise, <c>false</c>.</value>
public override bool IsAuthenticated {
get { return authenticated; }
}
#if !NETFX_CORE
bool ValidateRemoteCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (ServerCertificateValidationCallback != null)
return ServerCertificateValidationCallback (host, certificate, chain, sslPolicyErrors);
#if !COREFX
if (ServicePointManager.ServerCertificateValidationCallback != null)
return ServicePointManager.ServerCertificateValidationCallback (host, certificate, chain, sslPolicyErrors);
#endif
return DefaultServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
}
#endif
void QueueCommand (SmtpCommand type, string command, CancellationToken cancellationToken)
{
var bytes = Encoding.UTF8.GetBytes (command + "\r\n");
// Note: queued commands will be buffered by the stream
Stream.Write (bytes, 0, bytes.Length, cancellationToken);
queued.Add (type);
}
void FlushCommandQueue (MailboxAddress sender, IList<MailboxAddress> recipients, CancellationToken cancellationToken)
{
if (queued.Count == 0)
return;
try {
var responses = new List<SmtpResponse> ();
Exception rex = null;
int rcpt = 0;
// Note: queued commands are buffered by the stream
Stream.Flush (cancellationToken);
// Note: we need to read all responses from the server before we can process
// them in case any of them have any errors so that we can RSET the state.
try {
for (int i = 0; i < queued.Count; i++)
responses.Add (Stream.ReadResponse (cancellationToken));
} catch (Exception ex) {
// Note: save this exception for later (it may be related to
// an error response for a MAIL FROM or RCPT TO command).
rex = ex;
}
for (int i = 0; i < responses.Count; i++) {
switch (queued[i]) {
case SmtpCommand.MailFrom:
ProcessMailFromResponse (responses[i], sender);
break;
case SmtpCommand.RcptTo:
ProcessRcptToResponse (responses[i], recipients[rcpt++]);
break;
}
}
if (rex != null)
throw new SmtpProtocolException ("Error reading a response from the SMTP server.", rex);
} finally {
queued.Clear ();
}
}
SmtpResponse SendCommand (string command, CancellationToken cancellationToken)
{
var bytes = Encoding.UTF8.GetBytes (command + "\r\n");
Stream.Write (bytes, 0, bytes.Length, cancellationToken);
Stream.Flush (cancellationToken);
return Stream.ReadResponse (cancellationToken);
}
SmtpResponse SendEhlo (bool ehlo, CancellationToken cancellationToken)
{
string command = ehlo ? "EHLO " : "HELO ";
#if !NETFX_CORE
string domain = null;
IPAddress ip = null;
if (!string.IsNullOrEmpty (LocalDomain)) {
if (!IPAddress.TryParse (LocalDomain, out ip))
domain = LocalDomain;
} else if (Stream.Socket != null) {
var ipEndPoint = Stream.Socket.LocalEndPoint as IPEndPoint;
if (ipEndPoint == null)
domain = ((DnsEndPoint) Stream.Socket.LocalEndPoint).Host;
else
ip = ipEndPoint.Address;
} else {
domain = "[127.0.0.1]";
}
if (ip != null) {
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
domain = "[IPv6:" + ip + "]";
else
domain = "[" + ip + "]";
}
command += domain;
#else
if (!string.IsNullOrEmpty (LocalDomain))
command += LocalDomain;
if (Stream.Socket.Information.LocalAddress.IPInformation != null)
command += "[" + Stream.Socket.Information.LocalAddress.IPInformation + "]";
else
command += Stream.Socket.Information.LocalAddress.CanonicalName;
#endif
return SendCommand (command, cancellationToken);
}
void Ehlo (CancellationToken cancellationToken)
{
SmtpResponse response;
response = SendEhlo (true, cancellationToken);
// Some SMTP servers do not accept an EHLO after authentication (despite the rfc saying it is required).
if (response.StatusCode == SmtpStatusCode.BadCommandSequence && capabilities != SmtpCapabilities.None)
return;
if (response.StatusCode != SmtpStatusCode.Ok) {
// Try sending HELO instead...
response = SendEhlo (false, cancellationToken);
if (response.StatusCode != SmtpStatusCode.Ok)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
} else {
// Clear the extensions
capabilities = SmtpCapabilities.None;
AuthenticationMechanisms.Clear ();
MaxSize = 0;
var lines = response.Response.Split ('\n');
for (int i = 0; i < lines.Length; i++) {
// Outlook.com replies with "250-8bitmime" instead of "250-8BITMIME"
// (strangely, it correctly capitalizes all other extensions...)
var capability = lines[i].Trim ().ToUpperInvariant ();
if (capability.StartsWith ("AUTH", StringComparison.Ordinal)) {
int index = 4;
capabilities |= SmtpCapabilities.Authentication;
if (index < capability.Length && capability[index] == '=')
index++;
var mechanisms = capability.Substring (index);
foreach (var mechanism in mechanisms.Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
AuthenticationMechanisms.Add (mechanism);
} else if (capability.StartsWith ("SIZE", StringComparison.Ordinal)) {
int index = 4;
uint size;
capabilities |= SmtpCapabilities.Size;
while (index < capability.Length && char.IsWhiteSpace (capability[index]))
index++;
if (uint.TryParse (capability.Substring (index), out size))
MaxSize = size;
} else if (capability == "DSN") {
capabilities |= SmtpCapabilities.Dsn;
} else if (capability == "BINARYMIME") {
capabilities |= SmtpCapabilities.BinaryMime;
} else if (capability == "CHUNKING") {
capabilities |= SmtpCapabilities.Chunking;
} else if (capability == "ENHANCEDSTATUSCODES") {
capabilities |= SmtpCapabilities.EnhancedStatusCodes;
} else if (capability == "8BITMIME") {
capabilities |= SmtpCapabilities.EightBitMime;
} else if (capability == "PIPELINING") {
capabilities |= SmtpCapabilities.Pipelining;
} else if (capability == "STARTTLS") {
capabilities |= SmtpCapabilities.StartTLS;
} else if (capability == "SMTPUTF8") {
capabilities |= SmtpCapabilities.UTF8;
}
}
}
}
/// <summary>
/// Authenticates using the supplied credentials.
/// </summary>
/// <remarks>
/// <para>If the SMTP server supports authentication, then the SASL mechanisms
/// that both the client and server support are tried in order of greatest
/// security to weakest security. Once a SASL authentication mechanism is
/// found that both client and server support, the credentials are used to
/// authenticate.</para>
/// <para>If, on the other hand, authentication is not supported by the SMTP
/// server, then this method will throw <see cref="System.NotSupportedException"/>.
/// The <see cref="Capabilities"/> property can be checked for the
/// <see cref="SmtpCapabilities.Authentication"/> flag to make sure the
/// SMTP server supports authentication before calling this method.</para>
/// <note type="tip"> To prevent the usage of certain authentication mechanisms,
/// simply remove them from the <see cref="AuthenticationMechanisms"/> hash set
/// before calling this method.</note>
/// </remarks>
/// <param name="encoding">The text encoding to use for the user's credentials.</param>
/// <param name="credentials">The user's credentials.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="encoding"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="credentials"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="ServiceNotConnectedException">
/// The <see cref="SmtpClient"/> is not connected.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="SmtpClient"/> is already authenticated.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The SMTP server does not support authentication.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="MailKit.Security.AuthenticationException">
/// Authentication using the supplied credentials has failed.
/// </exception>
/// <exception cref="MailKit.Security.SaslException">
/// A SASL authentication error occurred.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="SmtpCommandException">
/// The SMTP command failed.
/// </exception>
/// <exception cref="SmtpProtocolException">
/// An SMTP protocol error occurred.
/// </exception>
public override void Authenticate (Encoding encoding, ICredentials credentials, CancellationToken cancellationToken = default (CancellationToken))
{
if (encoding == null)
throw new ArgumentNullException ("encoding");
if (credentials == null)
throw new ArgumentNullException ("credentials");
CheckDisposed ();
if (!IsConnected)
throw new ServiceNotConnectedException ("The SmtpClient must be connected before you can authenticate.");
if (IsAuthenticated)
throw new InvalidOperationException ("The SmtpClient is already authenticated.");
if ((capabilities & SmtpCapabilities.Authentication) == 0)
throw new NotSupportedException ("The SMTP server does not support authentication.");
var uri = new Uri ("smtp://" + host);
SaslException authException = null;
SmtpResponse response;
SaslMechanism sasl;
bool tried = false;
string challenge;
string command;
foreach (var authmech in SaslMechanism.AuthMechanismRank) {
if (!AuthenticationMechanisms.Contains (authmech))
continue;
if ((sasl = SaslMechanism.Create (authmech, uri, encoding, credentials)) == null)
continue;
tried = true;
cancellationToken.ThrowIfCancellationRequested ();
// send an initial challenge if the mechanism supports it
if (sasl.SupportsInitialResponse) {
challenge = sasl.Challenge (null);
command = string.Format ("AUTH {0} {1}", authmech, challenge);
} else {
command = string.Format ("AUTH {0}", authmech);
}
response = SendCommand (command, cancellationToken);
if (response.StatusCode == SmtpStatusCode.AuthenticationMechanismTooWeak)
continue;
try {
while (!sasl.IsAuthenticated) {
if (response.StatusCode != SmtpStatusCode.AuthenticationChallenge)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
challenge = sasl.Challenge (response.Response);
response = SendCommand (challenge, cancellationToken);
}
} catch (SaslException ex) {
// reset the authentication state
response = SendCommand (string.Empty, cancellationToken);
authException = ex;
}
if (response.StatusCode == SmtpStatusCode.AuthenticationSuccessful) {
// Note: smtp.strato.de is a broken piece of shit that resets state if it receives
// an EHLO command after authenticating even though the specifications explicitly
// state that clients SHOULD send EHLO again after authenticating.
// See https://github.com/jstedfast/MailKit/issues/162 for details.
//
// Apparently smtp.sina.com has the same problem. Don't you love non RFC-compliant mail servers?
if (host != "smtp.strato.de" && host != "smtp.sina.com")
Ehlo (cancellationToken);
authenticated = true;
OnAuthenticated (response.Response);
return;
}
}
if (tried)
throw authException ?? new AuthenticationException ();
throw new NotSupportedException ("No compatible authentication mechanisms found.");
}
internal void ReplayConnect (string hostName, Stream replayStream, CancellationToken cancellationToken = default (CancellationToken))
{
CheckDisposed ();
if (hostName == null)
throw new ArgumentNullException ("hostName");
if (replayStream == null)
throw new ArgumentNullException ("replayStream");
Stream = new SmtpStream (replayStream, null, ProtocolLogger);
capabilities = SmtpCapabilities.None;
AuthenticationMechanisms.Clear ();
host = hostName;
secure = false;
MaxSize = 0;
try {
// read the greeting
var response = Stream.ReadResponse (cancellationToken);
if (response.StatusCode != SmtpStatusCode.ServiceReady)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
// Send EHLO and get a list of supported extensions
Ehlo (cancellationToken);
connected = true;
} catch {
Stream.Dispose ();
Stream = null;
throw;
}
OnConnected ();
}
static void ComputeDefaultValues (string host, ref int port, ref SecureSocketOptions options, out Uri uri, out bool starttls)
{
switch (options) {
default:
if (port == 0)
port = 25;
break;
case SecureSocketOptions.Auto:
switch (port) {
case 0: port = 25; goto default;
case 465: options = SecureSocketOptions.SslOnConnect; break;
default: options = SecureSocketOptions.StartTlsWhenAvailable; break;
}
break;
case SecureSocketOptions.SslOnConnect:
if (port == 0)
port = 465;
break;
}
switch (options) {
case SecureSocketOptions.StartTlsWhenAvailable:
uri = new Uri ("smtp://" + host + ":" + port + "/?starttls=when-available");
starttls = true;
break;
case SecureSocketOptions.StartTls:
uri = new Uri ("smtp://" + host + ":" + port + "/?starttls=always");
starttls = true;
break;
case SecureSocketOptions.SslOnConnect:
uri = new Uri ("smtps://" + host + ":" + port);
starttls = false;
break;
default:
uri = new Uri ("smtp://" + host + ":" + port);
starttls = false;
break;
}
}
/// <summary>
/// Establishes a connection to the specified SMTP or SMTP/S server.
/// </summary>
/// <remarks>
/// <para>Establishes a connection to the specified SMTP or SMTP/S server.</para>
/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
/// <paramref name="options"/> parameter is used to determine the default port to
/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
/// is <c>465</c>. All other values will use a default port of <c>25</c>.</para>
/// <para>If the <paramref name="options"/> has a value of
/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
/// to determine the default security options. If the <paramref name="port"/> has a value
/// of <c>465</c>, then the default options used will be
/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
/// <para>Once a connection is established, properties such as
/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
/// populated.</para>
/// <note type="note">The connection established by any of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a>
/// methods may be re-used if an application wishes to send multiple messages
/// to the same SMTP server. Since connecting and authenticating can be expensive
/// operations, re-using a connection can significantly improve performance when
/// sending a large number of messages to the same SMTP server over a short
/// period of time.</note>
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessage"/>
/// </example>
/// <param name="host">The host name to connect to.</param>
/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
/// <param name="options">The secure socket options to when connecting.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The <see cref="SmtpClient"/> has been disposed.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="SmtpClient"/> is already connected.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <paramref name="options"/> was set to
/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
/// and the SMTP server does not support the STARTTLS extension.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="SmtpCommandException">
/// An SMTP command failed.
/// </exception>
/// <exception cref="SmtpProtocolException">
/// An SMTP protocol error occurred.
/// </exception>
public override void Connect (string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
{
if (host == null)
throw new ArgumentNullException ("host");
if (host.Length == 0)
throw new ArgumentException ("The host name cannot be empty.", "host");
if (port < 0 || port > 65535)
throw new ArgumentOutOfRangeException ("port");
CheckDisposed ();
if (IsConnected)
throw new InvalidOperationException ("The SmtpClient is already connected.");
capabilities = SmtpCapabilities.None;
AuthenticationMechanisms.Clear ();
MaxSize = 0;
SmtpResponse response;
Stream stream;
bool starttls;
Uri uri;
ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);
#if !NETFX_CORE
#if COREFX
var ipAddresses = Dns.GetHostAddressesAsync (uri.DnsSafeHost).GetAwaiter ().GetResult ();
#else
var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
#endif
Socket socket = null;
for (int i = 0; i < ipAddresses.Length; i++) {
socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try {
cancellationToken.ThrowIfCancellationRequested ();
if (LocalEndPoint != null)
socket.Bind (LocalEndPoint);
socket.Connect (ipAddresses[i], port);
break;
} catch (OperationCanceledException) {
socket.Dispose ();
socket = null;
throw;
} catch {
socket.Dispose ();
socket = null;
if (i + 1 == ipAddresses.Length)
throw;
}
}
if (socket == null)
throw new IOException (string.Format ("Failed to resolve host: {0}", host));
this.host = host;
if (options == SecureSocketOptions.SslOnConnect) {
var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
ssl.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
secure = true;
stream = ssl;
} else {
stream = new NetworkStream (socket, true);
secure = false;
}
#else
var protection = options == SecureSocketOptions.SslOnConnect ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
var socket = new StreamSocket ();
try {
cancellationToken.ThrowIfCancellationRequested ();
socket.ConnectAsync (new HostName (host), port.ToString (), protection)
.AsTask (cancellationToken)
.GetAwaiter ()
.GetResult ();
} catch {
socket.Dispose ();
throw;
}
stream = new DuplexStream (socket.InputStream.AsStreamForRead (0), socket.OutputStream.AsStreamForWrite (0));
#endif
if (stream.CanTimeout) {
stream.WriteTimeout = timeout;
stream.ReadTimeout = timeout;
}
ProtocolLogger.LogConnect (uri);
Stream = new SmtpStream (stream, socket, ProtocolLogger);
try {
// read the greeting
response = Stream.ReadResponse (cancellationToken);
if (response.StatusCode != SmtpStatusCode.ServiceReady)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
// Send EHLO and get a list of supported extensions
Ehlo (cancellationToken);
if (options == SecureSocketOptions.StartTls && (capabilities & SmtpCapabilities.StartTLS) == 0)
throw new NotSupportedException ("The SMTP server does not support the STARTTLS extension.");
if (starttls && (capabilities & SmtpCapabilities.StartTLS) != 0) {
response = SendCommand ("STARTTLS", cancellationToken);
if (response.StatusCode != SmtpStatusCode.ServiceReady)
throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
#if !NETFX_CORE
var tls = new SslStream (stream, false, ValidateRemoteCertificate);
tls.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
Stream.Stream = tls;
#else
socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (host))
.AsTask (cancellationToken)
.GetAwaiter ()
.GetResult ();
#endif
secure = true;
// Send EHLO again and get the new list of supported extensions
Ehlo (cancellationToken);
}
connected = true;
} catch {
Stream.Dispose ();
secure = false;
Stream = null;
throw;
}
OnConnected ();
}
#if !NETFX_CORE
/// <summary>
/// Establish a connection to the specified SMTP or SMTP/S server using the provided socket.
/// </summary>
/// <remarks>
/// <para>Establishes a connection to the specified SMTP or SMTP/S server.</para>
/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
/// <paramref name="options"/> parameter is used to determine the default port to
/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
/// is <c>465</c>. All other values will use a default port of <c>25</c>.</para>
/// <para>If the <paramref name="options"/> has a value of
/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
/// to determine the default security options. If the <paramref name="port"/> has a value
/// of <c>465</c>, then the default options used will be
/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
/// <para>Once a connection is established, properties such as
/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
/// populated.</para>
/// <note type="note">The connection established by any of the
/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a>
/// methods may be re-used if an application wishes to send multiple messages
/// to the same SMTP server. Since connecting and authenticating can be expensive
/// operations, re-using a connection can significantly improve performance when
/// sending a large number of messages to the same SMTP server over a short
/// period of time./</note>
/// </remarks>
/// <param name="socket">The socket to use for the connection.</param>
/// <param name="host">The host name to connect to.</param>
/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
/// <param name="options">The secure socket options to when connecting.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="socket"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="host"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="socket"/> is not connected.</para>
/// <para>-or-</para>
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// The <see cref="SmtpClient"/> has been disposed.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="SmtpClient"/> is already connected.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <paramref name="options"/> was set to
/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
/// and the SMTP server does not support the STARTTLS extension.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
/// <exception cref="SmtpCommandException">
/// An SMTP command failed.
/// </exception>
/// <exception cref="SmtpProtocolException">
/// An SMTP protocol error occurred.
/// </exception>
public void Connect (Socket socket, string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
{
if (socket == null)
throw new ArgumentNullException ("socket");
if (!socket.Connected)
throw new ArgumentException ("The socket is not connected.", "socket");
if (host == null)
throw new ArgumentNullException ("host");
if (host.Length == 0)
throw new ArgumentException ("The host name cannot be empty.", "host");