/
SmtpClient.cs
1031 lines (901 loc) · 34.4 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.NetworkInformation;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Mail
{
public delegate void SendCompletedEventHandler(object sender, AsyncCompletedEventArgs e);
public enum SmtpDeliveryMethod
{
Network,
SpecifiedPickupDirectory,
PickupDirectoryFromIis
}
// EAI Settings
public enum SmtpDeliveryFormat
{
SevenBit = 0, // Legacy
International = 1, // SMTPUTF8 - Email Address Internationalization (EAI)
}
[UnsupportedOSPlatform("browser")]
public class SmtpClient : IDisposable
{
private string? _host;
private int _port;
private int _timeout = 100000;
private bool _inCall;
private bool _cancelled;
private bool _timedOut;
private string? _targetName;
private SmtpDeliveryMethod _deliveryMethod = SmtpDeliveryMethod.Network;
private SmtpDeliveryFormat _deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
private string? _pickupDirectoryLocation;
private SmtpTransport _transport;
private MailMessage? _message; //required to prevent premature finalization
private MailWriter? _writer;
private MailAddressCollection? _recipients;
private SendOrPostCallback _onSendCompletedDelegate;
private Timer? _timer;
private ContextAwareResult? _operationCompletedResult;
private AsyncOperation? _asyncOp;
private static readonly AsyncCallback s_contextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
private const int DefaultPort = 25;
internal string _clientDomain;
private bool _disposed;
private ServicePoint? _servicePoint;
// (async only) For when only some recipients fail. We still send the e-mail to the others.
private SmtpFailedRecipientException? _failedRecipientException;
// ports above this limit are invalid
private const int MaxPortValue = 65535;
public event SendCompletedEventHandler? SendCompleted;
private bool _useDefaultCredentials;
private ICredentialsByHost? _customCredentials;
public SmtpClient()
{
Initialize();
}
public SmtpClient(string? host)
{
_host = host;
Initialize();
}
public SmtpClient(string? host, int port)
{
try
{
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_host = host;
_port = port;
Initialize();
}
finally
{
}
}
[MemberNotNull(nameof(_transport))]
[MemberNotNull(nameof(_onSendCompletedDelegate))]
[MemberNotNull(nameof(_clientDomain))]
private void Initialize()
{
_transport = new SmtpTransport(this);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, _transport);
_onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
if (!string.IsNullOrEmpty(_host))
{
_host = _host.Trim();
}
if (_port == 0)
{
_port = DefaultPort;
}
_targetName ??= "SMTPSVC/" + _host;
if (_clientDomain == null)
{
// We use the local host name as the default client domain
// for the client's EHLO or HELO message. This limits the
// information about the host that we share. Additionally, the
// FQDN is not available to us or useful to the server (internal
// machine connecting to public server).
// SMTP RFC's require ASCII only host names in the HELO/EHLO message.
string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName;
IdnMapping mapping = new IdnMapping();
try
{
clientDomainRaw = mapping.GetAscii(clientDomainRaw);
}
catch (ArgumentException) { }
// For some inputs GetAscii may fail (bad Unicode, etc). If that happens
// we must strip out any non-ASCII characters.
// If we end up with no characters left, we use the string "LocalHost". This
// matches Outlook behavior.
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < clientDomainRaw.Length; i++)
{
ch = clientDomainRaw[i];
if ((ushort)ch <= 0x7F)
sb.Append(ch);
}
if (sb.Length > 0)
_clientDomain = sb.ToString();
else
_clientDomain = "LocalHost";
}
}
[DisallowNull]
public string? Host
{
get
{
return _host;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
ArgumentException.ThrowIfNullOrEmpty(value);
value = value.Trim();
if (value != _host)
{
_host = value;
_servicePoint = null;
}
}
}
public int Port
{
get
{
return _port;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value != _port)
{
_port = value;
_servicePoint = null;
}
}
}
public bool UseDefaultCredentials
{
get
{
return _useDefaultCredentials;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_useDefaultCredentials = value;
UpdateTransportCredentials();
}
}
public ICredentialsByHost? Credentials
{
get
{
return _transport.Credentials;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_customCredentials = value;
UpdateTransportCredentials();
}
}
private void UpdateTransportCredentials()
{
_transport.Credentials = _useDefaultCredentials ? CredentialCache.DefaultNetworkCredentials : _customCredentials;
}
public int Timeout
{
get
{
return _timeout;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_timeout = value;
}
}
public ServicePoint ServicePoint
{
get
{
CheckHostAndPort();
// This differs from desktop, where it uses an internal overload of FindServicePoint that just
// takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
// creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
// This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
// be usable, whereas in .NET Framework it throws an exception that "This property is not supported for
// protocols that do not use URI."
#pragma warning disable SYSLIB0014
return _servicePoint ??= ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
#pragma warning restore SYSLIB0014
}
}
public SmtpDeliveryMethod DeliveryMethod
{
get
{
return _deliveryMethod;
}
set
{
_deliveryMethod = value;
}
}
public SmtpDeliveryFormat DeliveryFormat
{
get
{
return _deliveryFormat;
}
set
{
_deliveryFormat = value;
}
}
public string? PickupDirectoryLocation
{
get
{
return _pickupDirectoryLocation;
}
set
{
_pickupDirectoryLocation = value;
}
}
/// <summary>
/// <para>Set to true if we need SSL</para>
/// </summary>
public bool EnableSsl
{
get
{
return _transport.EnableSsl;
}
set
{
_transport.EnableSsl = value;
}
}
/// <summary>
/// Certificates used by the client for establishing an SSL connection with the server.
/// </summary>
public X509CertificateCollection ClientCertificates
{
get
{
return _transport.ClientCertificates;
}
}
public string? TargetName
{
get { return _targetName; }
set { _targetName = value; }
}
private bool ServerSupportsEai
{
get
{
return _transport.ServerSupportsEai;
}
}
private bool IsUnicodeSupported()
{
if (DeliveryMethod == SmtpDeliveryMethod.Network)
{
return (ServerSupportsEai && (DeliveryFormat == SmtpDeliveryFormat.International));
}
else
{ // Pickup directories
return (DeliveryFormat == SmtpDeliveryFormat.International);
}
}
internal MailWriter GetFileMailWriter(string? pickupDirectory)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{nameof(pickupDirectory)}={pickupDirectory}");
if (!Path.IsPathRooted(pickupDirectory))
throw new SmtpException(SR.SmtpNeedAbsolutePickupDirectory);
string filename;
string pathAndFilename;
while (true)
{
filename = $"{Guid.NewGuid()}.eml";
pathAndFilename = Path.Combine(pickupDirectory, filename);
if (!File.Exists(pathAndFilename))
break;
}
FileStream fileStream = new FileStream(pathAndFilename, FileMode.CreateNew);
return new MailWriter(fileStream, encodeForTransport: false);
}
protected void OnSendCompleted(AsyncCompletedEventArgs e)
{
SendCompleted?.Invoke(this, e);
}
private void SendCompletedWaitCallback(object? operationState)
{
OnSendCompleted((AsyncCompletedEventArgs)operationState!);
}
public void Send(string from, string recipients, string? subject, string? body)
{
ObjectDisposedException.ThrowIf(_disposed, this);
//validation happens in MailMessage constructor
MailMessage mailMessage = new MailMessage(from, recipients, subject, body);
Send(mailMessage);
}
public void Send(MailMessage message)
{
ArgumentNullException.ThrowIfNull(message);
ObjectDisposedException.ThrowIf(_disposed, this);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
NetEventSource.Associate(this, message);
}
SmtpFailedRecipientException? recipientException = null;
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
MailAddressCollection recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
recipients.Add(address);
}
}
if (recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
_transport.IdentityRequired = false; // everything completes on the same thread.
try
{
InCall = true;
_timedOut = false;
_timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
bool allowUnicode = false;
string? pickupDirectory = PickupDirectoryLocation;
MailWriter writer;
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
allowUnicode = IsUnicodeSupported(); // Determined by the DeliveryFormat parameter
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = GetFileMailWriter(pickupDirectory);
break;
case SmtpDeliveryMethod.Network:
default:
GetConnection();
// Detected during GetConnection(), restrictable using the DeliveryFormat parameter
allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = _transport.SendMail(message.Sender ?? message.From, recipients,
message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
break;
}
_message = message;
message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
writer.Close();
//throw if we couldn't send to any of the recipients
if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
{
throw recipientException;
}
}
catch (Exception e)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (_timedOut)
{
throw new SmtpException(SR.net_timeout);
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
finally
{
InCall = false;
_timer?.Dispose();
}
}
public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
SendAsync(new MailMessage(from, recipients, subject, body), userToken);
}
public void SendAsync(MailMessage message, object? userToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
try
{
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
ArgumentNullException.ThrowIfNull(message);
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
_recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
_recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
_recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
_recipients.Add(address);
}
}
if (_recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
InCall = true;
_cancelled = false;
_message = message;
string? pickupDirectory = PickupDirectoryLocation;
CredentialCache? cache;
// Skip token capturing if no credentials are used or they don't include a default one.
// Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
_transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
_asyncOp = AsyncOperationManager.CreateOperation(userToken);
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
{
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
_writer = GetFileMailWriter(pickupDirectory);
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, _recipients, allowUnicode);
message.Send(_writer, true, allowUnicode);
_writer?.Close();
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
InCall = false;
_asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
break;
}
case SmtpDeliveryMethod.Network:
default:
_operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
lock (_operationCompletedResult.StartPostingAsyncOp())
{
if (_transport.IsConnected)
{
try
{
SendMailAsync(_operationCompletedResult);
}
catch (Exception e)
{
Complete(e, _operationCompletedResult);
}
}
else
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
_transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
}
_operationCompletedResult.FinishPostingAsyncOp();
}
break;
}
}
catch (Exception e)
{
InCall = false;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
}
private static bool IsSystemNetworkCredentialInCache(CredentialCache cache)
{
// Check if SystemNetworkCredential is in given cache.
foreach (NetworkCredential credential in cache)
{
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
return true;
}
}
return false;
}
public void SendAsyncCancel()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!InCall || _cancelled)
{
return;
}
_cancelled = true;
Abort();
}
//************* Task-based async public methods *************************
public Task SendMailAsync(string from, string recipients, string? subject, string? body)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message, cancellationToken: default);
}
public Task SendMailAsync(MailMessage message)
{
return SendMailAsync(message, cancellationToken: default);
}
public Task SendMailAsync(string from, string recipients, string? subject, string? body, CancellationToken cancellationToken)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message, cancellationToken);
}
public Task SendMailAsync(MailMessage message, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
// Create a TaskCompletionSource to represent the operation
var tcs = new TaskCompletionSource();
CancellationTokenRegistration ctr = default;
// Indicates whether the CTR has been set - captured in handler
int state = 0;
// Register a handler that will transfer completion results to the TCS Task
SendCompletedEventHandler? handler = null;
handler = (sender, e) =>
{
if (e.UserState == tcs)
{
try
{
((SmtpClient)sender).SendCompleted -= handler;
if (Interlocked.Exchange(ref state, 1) != 0)
{
// A CTR has been set, we have to wait until it completes before completing the task
ctr.Dispose();
}
}
catch (ObjectDisposedException) { } // SendAsyncCancel will throw if SmtpClient was disposed
finally
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult();
}
}
};
SendCompleted += handler;
// Start the async operation.
try
{
SendAsync(message, tcs);
}
catch
{
SendCompleted -= handler;
throw;
}
ctr = cancellationToken.Register(s =>
{
((SmtpClient)s!).SendAsyncCancel();
}, this);
if (Interlocked.Exchange(ref state, 1) != 0)
{
// SendCompleted was already invoked, ensure the CTR completes before returning the task
ctr.Dispose();
}
// Return the task to represent the asynchronous operation
return tcs.Task;
}
//*********************************
// private methods
//********************************
internal bool InCall
{
get
{
return _inCall;
}
set
{
_inCall = value;
}
}
private void CheckHostAndPort()
{
if (_host == null || _host.Length == 0)
{
throw new InvalidOperationException(SR.UnspecifiedHost);
}
if (_port <= 0 || _port > MaxPortValue)
{
throw new InvalidOperationException(SR.InvalidPort);
}
}
private void TimeOutCallback(object? state)
{
if (!_timedOut)
{
_timedOut = true;
Abort();
}
}
private void Complete(Exception? exception, object result)
{
ContextAwareResult operationCompletedResult = (ContextAwareResult)result;
try
{
if (_cancelled)
{
//any exceptions were probably caused by cancellation, clear it.
exception = null;
Abort();
}
// An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, exception);
Abort();
if (!(exception is SmtpException))
{
exception = new SmtpException(SR.SmtpSendMailFailure, exception);
}
}
else
{
if (_writer != null)
{
try
{
_writer.Close();
}
// Close may result in a DataStopCommand and the server may return error codes at this time.
catch (SmtpException se)
{
exception = se;
}
}
}
}
finally
{
operationCompletedResult.InvokeCallback(exception);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Complete");
}
private static void ContextSafeCompleteCallback(IAsyncResult ar)
{
ContextAwareResult result = (ContextAwareResult)ar;
SmtpClient client = (SmtpClient)ar.AsyncState!;
Exception? exception = result.Result as Exception;
AsyncOperation asyncOp = client._asyncOp!;
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);
client.InCall = false;
client._failedRecipientException = null; // Reset before the next send.
asyncOp.PostOperationCompleted(client._onSendCompletedDelegate, eventArgs);
}
private void SendMessageCallback(IAsyncResult result)
{
try
{
_message!.EndSend(result);
// If some recipients failed but not others, throw AFTER sending the message.
Complete(_failedRecipientException, result.AsyncState!);
}
catch (Exception e)
{
Complete(e, result.AsyncState!);
}
}
private void SendMailCallback(IAsyncResult result)
{
try
{
_writer = SmtpTransport.EndSendMail(result);
// If some recipients failed but not others, send the e-mail anyway, but then return the
// "Non-fatal" exception reporting the failures. The sync code path does it this way.
// Fatal exceptions would have thrown above at transport.EndSendMail(...)
SendMailAsyncResult sendResult = (SendMailAsyncResult)result;
// Save these and throw them later in SendMessageCallback, after the message has sent.
_failedRecipientException = sendResult.GetFailedRecipientException();
}
catch (Exception e)
{
Complete(e, result.AsyncState!);
return;
}
try
{
if (_cancelled)
{
Complete(null, result.AsyncState!);
}
else
{
_message!.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState!);
}
}
catch (Exception e)
{
Complete(e, result.AsyncState!);
}
}
private void ConnectCallback(IAsyncResult result)
{
try
{
SmtpTransport.EndGetConnection(result);
if (_cancelled)
{
Complete(null, result.AsyncState!);
}
else
{
SendMailAsync(result.AsyncState!);
}
}
catch (Exception e)
{
Complete(e, result.AsyncState!);
}
}
private void SendMailAsync(object state)
{
// Detected during Begin/EndGetConnection, restrictable using DeliveryFormat
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(_message!, _recipients!, allowUnicode);
_transport.BeginSendMail(_message!.Sender ?? _message.From!, _recipients!,
_message.BuildDeliveryStatusNotificationString(), allowUnicode,
new AsyncCallback(SendMailCallback), state);
}
// After we've estabilished a connection and initialized ServerSupportsEai,
// check all the addresses for one that contains unicode in the username/localpart.
// The localpart is the only thing we cannot successfully downgrade.
private static void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode)
{
// Check all recipients, to, from, sender, bcc, cc, etc...
// GetSmtpAddress will throw if !allowUnicode and the username contains non-ascii
foreach (MailAddress address in recipients)
{
address.GetSmtpAddress(allowUnicode);
}
message.Sender?.GetSmtpAddress(allowUnicode);
message.From!.GetSmtpAddress(allowUnicode);
}
private void GetConnection()
{
if (!_transport.IsConnected)
{