Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
SmtpClient.cs
Go to the documentation of this file.
4using System.IO;
11using System.Text;
14
15namespace System.Net.Mail;
16
17[UnsupportedOSPlatform("browser")]
18public class SmtpClient : IDisposable
19{
20 private string _host;
21
22 private int _port;
23
24 private int _timeout = 100000;
25
26 private bool _inCall;
27
28 private bool _cancelled;
29
30 private bool _timedOut;
31
32 private string _targetName;
33
35
37
39
41
43
45
47
48 private SendOrPostCallback _onSendCompletedDelegate;
49
50 private Timer _timer;
51
53
55
56 private static readonly AsyncCallback s_contextSafeCompleteCallback = ContextSafeCompleteCallback;
57
58 internal string _clientDomain;
59
60 private bool _disposed;
61
63
65
67
69
70 public string? Host
71 {
72 get
73 {
74 return _host;
75 }
76 [param: DisallowNull]
77 set
78 {
79 if (InCall)
80 {
82 }
83 if (value == null)
84 {
85 throw new ArgumentNullException("value");
86 }
87 if (value.Length == 0)
88 {
90 }
91 value = value.Trim();
92 if (value != _host)
93 {
94 _host = value;
95 _servicePoint = null;
96 }
97 }
98 }
99
100 public int Port
101 {
102 get
103 {
104 return _port;
105 }
106 set
107 {
108 if (InCall)
109 {
111 }
112 if (value <= 0)
113 {
114 throw new ArgumentOutOfRangeException("value");
115 }
116 if (value != _port)
117 {
118 _port = value;
119 _servicePoint = null;
120 }
121 }
122 }
123
125 {
126 get
127 {
129 }
130 set
131 {
132 if (InCall)
133 {
135 }
138 }
139 }
140
142 {
143 get
144 {
145 return _transport.Credentials;
146 }
147 set
148 {
149 if (InCall)
150 {
152 }
155 }
156 }
157
158 public int Timeout
159 {
160 get
161 {
162 return _timeout;
163 }
164 set
165 {
166 if (InCall)
167 {
169 }
170 if (value < 0)
171 {
172 throw new ArgumentOutOfRangeException("value");
173 }
174 _timeout = value;
175 }
176 }
177
179 {
180 get
181 {
183 return _servicePoint ?? (_servicePoint = ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port)));
184 }
185 }
186
188 {
189 get
190 {
191 return _deliveryMethod;
192 }
193 set
194 {
196 }
197 }
198
200 {
201 get
202 {
203 return _deliveryFormat;
204 }
205 set
206 {
208 }
209 }
210
212 {
213 get
214 {
216 }
217 set
218 {
220 }
221 }
222
223 public bool EnableSsl
224 {
225 get
226 {
227 return _transport.EnableSsl;
228 }
229 set
230 {
231 _transport.EnableSsl = value;
232 }
233 }
234
236
237 public string? TargetName
238 {
239 get
240 {
241 return _targetName;
242 }
243 set
244 {
246 }
247 }
248
250
251 internal bool InCall
252 {
253 get
254 {
255 return _inCall;
256 }
257 set
258 {
259 _inCall = value;
260 }
261 }
262
264
265 public SmtpClient()
266 {
267 Initialize();
268 }
269
270 public SmtpClient(string? host)
271 {
272 _host = host;
273 Initialize();
274 }
275
276 public SmtpClient(string? host, int port)
277 {
278 if (port < 0)
279 {
280 throw new ArgumentOutOfRangeException("port");
281 }
282 _host = host;
283 _port = port;
284 Initialize();
285 }
286
287 [MemberNotNull("_transport")]
288 [MemberNotNull("_onSendCompletedDelegate")]
289 [MemberNotNull("_clientDomain")]
290 private void Initialize()
291 {
292 _transport = new SmtpTransport(this);
293 if (System.Net.NetEventSource.Log.IsEnabled())
294 {
295 System.Net.NetEventSource.Associate(this, _transport, "Initialize");
296 }
298 if (_host != null && _host.Length != 0)
299 {
300 _host = _host.Trim();
301 }
302 if (_port == 0)
303 {
304 _port = 25;
305 }
306 if (_targetName == null)
307 {
308 _targetName = "SMTPSVC/" + _host;
309 }
310 if (_clientDomain != null)
311 {
312 return;
313 }
315 IdnMapping idnMapping = new IdnMapping();
316 try
317 {
318 text = idnMapping.GetAscii(text);
319 }
320 catch (ArgumentException)
321 {
322 }
323 StringBuilder stringBuilder = new StringBuilder();
324 foreach (char c in text)
325 {
326 if (c <= '\u007f')
327 {
328 stringBuilder.Append(c);
329 }
330 }
331 if (stringBuilder.Length > 0)
332 {
333 _clientDomain = stringBuilder.ToString();
334 }
335 else
336 {
337 _clientDomain = "LocalHost";
338 }
339 }
340
342 {
343 SmtpTransport transport = _transport;
344 ICredentialsByHost credentials;
346 {
347 credentials = _customCredentials;
348 }
349 else
350 {
352 credentials = defaultNetworkCredentials;
353 }
354 transport.Credentials = credentials;
355 }
356
357 private bool IsUnicodeSupported()
358 {
359 if (DeliveryMethod == SmtpDeliveryMethod.Network)
360 {
362 {
363 return DeliveryFormat == SmtpDeliveryFormat.International;
364 }
365 return false;
366 }
367 return DeliveryFormat == SmtpDeliveryFormat.International;
368 }
369
370 internal MailWriter GetFileMailWriter(string pickupDirectory)
371 {
372 if (System.Net.NetEventSource.Log.IsEnabled())
373 {
374 System.Net.NetEventSource.Info(this, FormattableStringFactory.Create("{0}={1}", "pickupDirectory", pickupDirectory), "GetFileMailWriter");
375 }
376 if (!Path.IsPathRooted(pickupDirectory))
377 {
379 }
380 string path2;
381 do
382 {
383 string path = $"{Guid.NewGuid()}.eml";
384 path2 = Path.Combine(pickupDirectory, path);
385 }
386 while (File.Exists(path2));
387 FileStream stream = new FileStream(path2, FileMode.CreateNew);
388 return new MailWriter(stream, encodeForTransport: false);
389 }
390
392 {
393 this.SendCompleted?.Invoke(this, e);
394 }
395
396 private void SendCompletedWaitCallback(object operationState)
397 {
399 }
400
401 public void Send(string from, string recipients, string? subject, string? body)
402 {
403 if (_disposed)
404 {
405 throw new ObjectDisposedException(GetType().FullName);
406 }
407 MailMessage message = new MailMessage(from, recipients, subject, body);
408 Send(message);
409 }
410
411 public void Send(MailMessage message)
412 {
413 if (_disposed)
414 {
415 throw new ObjectDisposedException(GetType().FullName);
416 }
417 if (System.Net.NetEventSource.Log.IsEnabled())
418 {
419 System.Net.NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}", "Send");
420 System.Net.NetEventSource.Associate(this, message, "Send");
421 }
423 if (InCall)
424 {
426 }
427 if (message == null)
428 {
429 throw new ArgumentNullException("message");
430 }
431 if (DeliveryMethod == SmtpDeliveryMethod.Network)
432 {
434 }
435 MailAddressCollection mailAddressCollection = new MailAddressCollection();
436 if (message.From == null)
437 {
439 }
440 if (message.To != null)
441 {
442 foreach (MailAddress item in message.To)
443 {
444 mailAddressCollection.Add(item);
445 }
446 }
447 if (message.Bcc != null)
448 {
449 foreach (MailAddress item2 in message.Bcc)
450 {
451 mailAddressCollection.Add(item2);
452 }
453 }
454 if (message.CC != null)
455 {
456 foreach (MailAddress item3 in message.CC)
457 {
458 mailAddressCollection.Add(item3);
459 }
460 }
461 if (mailAddressCollection.Count == 0)
462 {
464 }
465 _transport.IdentityRequired = false;
466 try
467 {
468 InCall = true;
469 _timedOut = false;
471 bool flag = false;
472 string pickupDirectoryLocation = PickupDirectoryLocation;
473 MailWriter mailWriter;
474 switch (DeliveryMethod)
475 {
476 case SmtpDeliveryMethod.PickupDirectoryFromIis:
478 case SmtpDeliveryMethod.SpecifiedPickupDirectory:
479 if (EnableSsl)
480 {
482 }
483 flag = IsUnicodeSupported();
484 ValidateUnicodeRequirement(message, mailAddressCollection, flag);
485 mailWriter = GetFileMailWriter(pickupDirectoryLocation);
486 break;
487 default:
489 flag = IsUnicodeSupported();
490 ValidateUnicodeRequirement(message, mailAddressCollection, flag);
491 mailWriter = _transport.SendMail(message.Sender ?? message.From, mailAddressCollection, message.BuildDeliveryStatusNotificationString(), flag, out exception);
492 break;
493 }
494 _message = message;
495 message.Send(mailWriter, DeliveryMethod != SmtpDeliveryMethod.Network, flag);
496 mailWriter.Close();
497 if (DeliveryMethod == SmtpDeliveryMethod.Network && exception != null)
498 {
499 throw exception;
500 }
501 }
502 catch (Exception ex)
503 {
504 if (System.Net.NetEventSource.Log.IsEnabled())
505 {
506 System.Net.NetEventSource.Error(this, ex, "Send");
507 }
509 {
510 throw;
511 }
512 Abort();
513 if (_timedOut)
514 {
516 }
517 if (ex is SecurityException || ex is AuthenticationException || ex is SmtpException)
518 {
519 throw;
520 }
522 }
523 finally
524 {
525 InCall = false;
526 if (_timer != null)
527 {
528 _timer.Dispose();
529 }
530 }
531 }
532
533 public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken)
534 {
535 if (_disposed)
536 {
537 throw new ObjectDisposedException(GetType().FullName);
538 }
539 SendAsync(new MailMessage(from, recipients, subject, body), userToken);
540 }
541
542 public void SendAsync(MailMessage message, object? userToken)
543 {
544 if (_disposed)
545 {
546 throw new ObjectDisposedException(GetType().FullName);
547 }
548 try
549 {
550 if (InCall)
551 {
553 }
554 if (message == null)
555 {
556 throw new ArgumentNullException("message");
557 }
558 if (DeliveryMethod == SmtpDeliveryMethod.Network)
559 {
561 }
563 if (message.From == null)
564 {
566 }
567 if (message.To != null)
568 {
569 foreach (MailAddress item in message.To)
570 {
572 }
573 }
574 if (message.Bcc != null)
575 {
576 foreach (MailAddress item2 in message.Bcc)
577 {
578 _recipients.Add(item2);
579 }
580 }
581 if (message.CC != null)
582 {
583 foreach (MailAddress item3 in message.CC)
584 {
585 _recipients.Add(item3);
586 }
587 }
588 if (_recipients.Count == 0)
589 {
591 }
592 InCall = true;
593 _cancelled = false;
594 _message = message;
595 string pickupDirectoryLocation = PickupDirectoryLocation;
596 _transport.IdentityRequired = Credentials != null && (Credentials == CredentialCache.DefaultNetworkCredentials || !(Credentials is CredentialCache cache) || IsSystemNetworkCredentialInCache(cache));
598 switch (DeliveryMethod)
599 {
600 case SmtpDeliveryMethod.PickupDirectoryFromIis:
602 case SmtpDeliveryMethod.SpecifiedPickupDirectory:
603 {
604 if (EnableSsl)
605 {
607 }
608 _writer = GetFileMailWriter(pickupDirectoryLocation);
609 bool allowUnicode = IsUnicodeSupported();
610 ValidateUnicodeRequirement(message, _recipients, allowUnicode);
611 message.Send(_writer, sendEnvelope: true, allowUnicode);
612 if (_writer != null)
613 {
614 _writer.Close();
615 }
617 InCall = false;
619 return;
620 }
621 }
623 lock (_operationCompletedResult.StartPostingAsyncOp())
624 {
625 if (System.Net.NetEventSource.Log.IsEnabled())
626 {
627 System.Net.NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}", "SendAsync");
628 }
630 _operationCompletedResult.FinishPostingAsyncOp();
631 }
632 }
633 catch (Exception ex)
634 {
635 InCall = false;
636 if (System.Net.NetEventSource.Log.IsEnabled())
637 {
638 System.Net.NetEventSource.Error(this, ex, "SendAsync");
639 }
641 {
642 throw;
643 }
644 Abort();
645 if (ex is SecurityException || ex is AuthenticationException || ex is SmtpException)
646 {
647 throw;
648 }
650 }
651 }
652
654 {
655 foreach (NetworkCredential item in cache)
656 {
658 {
659 return true;
660 }
661 }
662 return false;
663 }
664
665 public void SendAsyncCancel()
666 {
667 if (_disposed)
668 {
669 throw new ObjectDisposedException(GetType().FullName);
670 }
671 if (InCall && !_cancelled)
672 {
673 _cancelled = true;
674 Abort();
675 }
676 }
677
678 public Task SendMailAsync(string from, string recipients, string? subject, string? body)
679 {
680 MailMessage message = new MailMessage(from, recipients, subject, body);
681 return SendMailAsync(message, default(CancellationToken));
682 }
683
685 {
686 return SendMailAsync(message, default(CancellationToken));
687 }
688
689 public Task SendMailAsync(string from, string recipients, string? subject, string? body, CancellationToken cancellationToken)
690 {
691 MailMessage message = new MailMessage(from, recipients, subject, body);
692 return SendMailAsync(message, cancellationToken);
693 }
694
696 {
697 if (cancellationToken.IsCancellationRequested)
698 {
700 }
703 int state = 0;
704 SendCompletedEventHandler handler = null;
705 handler = delegate(object sender, AsyncCompletedEventArgs e)
706 {
707 if (e.UserState == tcs)
708 {
709 try
710 {
711 ((SmtpClient)sender).SendCompleted -= handler;
712 if (Interlocked.Exchange(ref state, 1) != 0)
713 {
714 ctr.Dispose();
715 }
716 }
718 {
719 }
720 finally
721 {
722 if (e.Error != null)
723 {
724 tcs.TrySetException(e.Error);
725 }
726 else if (e.Cancelled)
727 {
728 tcs.TrySetCanceled();
729 }
730 else
731 {
732 tcs.TrySetResult();
733 }
734 }
735 }
736 };
737 SendCompleted += handler;
738 try
739 {
740 SendAsync(message, tcs);
741 }
742 catch
743 {
744 SendCompleted -= handler;
745 throw;
746 }
747 ctr = cancellationToken.Register(delegate(object s)
748 {
749 ((SmtpClient)s).SendAsyncCancel();
750 }, this);
751 if (Interlocked.Exchange(ref state, 1) != 0)
752 {
753 ctr.Dispose();
754 }
755 return tcs.Task;
756 }
757
758 private void CheckHostAndPort()
759 {
760 if (_host == null || _host.Length == 0)
761 {
763 }
764 if (_port <= 0 || _port > 65535)
765 {
767 }
768 }
769
770 private void TimeOutCallback(object state)
771 {
772 if (!_timedOut)
773 {
774 _timedOut = true;
775 Abort();
776 }
777 }
778
780 {
782 try
783 {
784 if (_cancelled)
785 {
786 exception = null;
787 Abort();
788 }
790 {
791 if (System.Net.NetEventSource.Log.IsEnabled())
792 {
793 System.Net.NetEventSource.Error(this, exception, "Complete");
794 }
795 Abort();
796 if (!(exception is SmtpException))
797 {
799 }
800 }
801 else if (_writer != null)
802 {
803 try
804 {
805 _writer.Close();
806 }
807 catch (SmtpException ex)
808 {
809 exception = ex;
810 }
811 }
812 }
813 finally
814 {
815 contextAwareResult.InvokeCallback(exception);
816 }
817 if (System.Net.NetEventSource.Log.IsEnabled())
818 {
819 System.Net.NetEventSource.Info(this, "Complete", "Complete");
820 }
821 }
822
824 {
826 SmtpClient smtpClient = (SmtpClient)ar.AsyncState;
827 Exception error = contextAwareResult.Result as Exception;
828 AsyncOperation asyncOp = smtpClient._asyncOp;
830 smtpClient.InCall = false;
831 smtpClient._failedRecipientException = null;
832 asyncOp.PostOperationCompleted(smtpClient._onSendCompletedDelegate, arg);
833 }
834
836 {
837 try
838 {
839 _message.EndSend(result);
841 }
842 catch (Exception exception)
843 {
844 Complete(exception, result);
845 }
846 }
847
848 private void SendMailCallback(IAsyncResult result)
849 {
850 try
851 {
853 SendMailAsyncResult sendMailAsyncResult = (SendMailAsyncResult)result;
855 }
856 catch (Exception exception)
857 {
858 Complete(exception, result);
859 return;
860 }
861 try
862 {
863 if (_cancelled)
864 {
865 Complete(null, result);
866 }
867 else
868 {
870 }
871 }
872 catch (Exception exception2)
873 {
874 Complete(exception2, result);
875 }
876 }
877
878 private void ConnectCallback(IAsyncResult result)
879 {
880 try
881 {
883 if (_cancelled)
884 {
885 Complete(null, result);
886 return;
887 }
888 bool allowUnicode = IsUnicodeSupported();
891 }
892 catch (Exception exception)
893 {
894 Complete(exception, result);
895 }
896 }
897
898 private void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode)
899 {
900 foreach (MailAddress recipient in recipients)
901 {
902 recipient.GetSmtpAddress(allowUnicode);
903 }
904 message.Sender?.GetSmtpAddress(allowUnicode);
905 message.From.GetSmtpAddress(allowUnicode);
906 }
907
908 private void GetConnection()
909 {
911 {
913 }
914 }
915
916 private void Abort()
917 {
919 }
920
921 public void Dispose()
922 {
923 Dispose(disposing: true);
924 GC.SuppressFinalize(this);
925 }
926
927 protected virtual void Dispose(bool disposing)
928 {
929 if (disposing && !_disposed)
930 {
931 if (InCall && !_cancelled)
932 {
933 _cancelled = true;
934 Abort();
935 }
936 else
937 {
939 }
940 _timer?.Dispose();
941 _disposed = true;
942 }
943 }
944}
static AsyncOperation CreateOperation(object? userSuppliedState)
void PostOperationCompleted(SendOrPostCallback d, object? arg)
static void SuppressFinalize(object obj)
Definition GC.cs:202
Definition GC.cs:8
string GetAscii(string unicode)
Definition IdnMapping.cs:44
static bool Exists([NotNullWhen(true)] string? path)
Definition File.cs:97
static string Combine(string path1, string path2)
Definition Path.cs:304
static bool IsPathRooted([NotNullWhen(true)] string? path)
Definition Path.cs:985
static NetworkCredential DefaultNetworkCredentials
void InvokeCallback(object result)
string GetSmtpAddress(bool allowUnicode)
void EndSend(IAsyncResult asyncResult)
MailAddressCollection Bcc
void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode)
MailAddressCollection To
string BuildDeliveryStatusNotificationString()
MailAddressCollection CC
IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode, AsyncCallback callback, object state)
override void Close()
Definition MailWriter.cs:31
SmtpFailedRecipientException GetFailedRecipientException()
Task SendMailAsync(MailMessage message, CancellationToken cancellationToken)
SendCompletedEventHandler? SendCompleted
virtual void Dispose(bool disposing)
SendOrPostCallback _onSendCompletedDelegate
Definition SmtpClient.cs:48
SmtpDeliveryFormat DeliveryFormat
void SendCompletedWaitCallback(object operationState)
void Send(string from, string recipients, string? subject, string? body)
SmtpDeliveryMethod DeliveryMethod
void Complete(Exception exception, IAsyncResult result)
void SendAsync(string from, string recipients, string? subject, string? body, object? userToken)
void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode)
void Send(MailMessage message)
SmtpDeliveryMethod _deliveryMethod
Definition SmtpClient.cs:34
void ConnectCallback(IAsyncResult result)
MailWriter GetFileMailWriter(string pickupDirectory)
X509CertificateCollection ClientCertificates
void OnSendCompleted(AsyncCompletedEventArgs e)
SmtpDeliveryFormat _deliveryFormat
Definition SmtpClient.cs:36
System.Net.ContextAwareResult _operationCompletedResult
Definition SmtpClient.cs:52
Task SendMailAsync(MailMessage message)
bool IsSystemNetworkCredentialInCache(CredentialCache cache)
ICredentialsByHost _customCredentials
Definition SmtpClient.cs:68
static void ContextSafeCompleteCallback(IAsyncResult ar)
static readonly AsyncCallback s_contextSafeCompleteCallback
Definition SmtpClient.cs:56
AsyncOperation _asyncOp
Definition SmtpClient.cs:54
Task SendMailAsync(string from, string recipients, string? subject, string? body, CancellationToken cancellationToken)
Task SendMailAsync(string from, string recipients, string? subject, string? body)
SmtpFailedRecipientException _failedRecipientException
Definition SmtpClient.cs:64
SmtpClient(string? host, int port)
void SendMailCallback(IAsyncResult result)
MailAddressCollection _recipients
Definition SmtpClient.cs:46
void SendAsync(MailMessage message, object? userToken)
void SendMessageCallback(IAsyncResult result)
void TimeOutCallback(object state)
ICredentialsByHost? Credentials
ICredentialsByHost Credentials
MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, out SmtpFailedRecipientException exception)
void EndGetConnection(IAsyncResult result)
IAsyncResult BeginGetConnection(System.Net.ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
MailWriter EndSendMail(IAsyncResult result)
X509CertificateCollection ClientCertificates
IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
void GetConnection(string host, int port)
static readonly System.Net.NetEventSource Log
static void Info(object thisOrContextObject, FormattableString formattableString=null, [CallerMemberName] string memberName=null)
static void Error(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName=null)
static void Associate(object first, object second, [CallerMemberName] string memberName=null)
static ServicePoint FindServicePoint(Uri address)
static FormattableString Create(string format, params object?[] arguments)
static string SmtpNeedAbsolutePickupDirectory
Definition SR.cs:102
static string InvalidPort
Definition SR.cs:58
static string net_inasync
Definition SR.cs:64
static string UnspecifiedHost
Definition SR.cs:132
static string SmtpGetIisPickupDirectoryNotSupported
Definition SR.cs:172
static string SmtpFromRequired
Definition SR.cs:82
static string net_timeout
Definition SR.cs:66
static string SmtpSendMailFailure
Definition SR.cs:114
static string SmtpRecipientRequired
Definition SR.cs:112
static string SmtpInvalidOperationDuringSend
Definition SR.cs:90
static string net_emptystringset
Definition SR.cs:20
static string SmtpPickupDirectoryDoesnotSupportSsl
Definition SR.cs:108
Definition SR.cs:7
static int Exchange(ref int location1, int value)
static Task FromCanceled(CancellationToken cancellationToken)
Definition Task.cs:3363
bool Dispose(WaitHandle notifyObject)
Definition Timer.cs:176
delegate void SendCompletedEventHandler(object sender, AsyncCompletedEventArgs e)