Merge pull request #2869 from BrzVlad/feature-mod-union-opt
[mono.git] / mcs / class / System / System.Net.Mail / SmtpClient.cs
1 //
2 // System.Net.Mail.SmtpClient.cs
3 //
4 // Author:
5 //      Tim Coleman (tim@timcoleman.com)
6 //
7 // Copyright (C) Tim Coleman, 2004
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 #if SECURITY_DEP
32 #if MONO_SECURITY_ALIAS
33 extern alias MonoSecurity;
34 #endif
35
36 #if MONO_SECURITY_ALIAS
37 using MSI = MonoSecurity::Mono.Security.Interface;
38 #else
39 using MSI = Mono.Security.Interface;
40 #endif
41 using System.Security.Cryptography.X509Certificates;
42 #endif
43
44 using System;
45 using System.Collections.Generic;
46 using System.ComponentModel;
47 using System.Globalization;
48 using System.IO;
49 using System.Net;
50 using System.Net.Mime;
51 using System.Net.Sockets;
52 using System.Text;
53 using System.Threading;
54 using System.Net.Configuration;
55 using System.Configuration;
56 using System.Net.Security;
57 using System.Security.Authentication;
58 using System.Threading.Tasks;
59 using Mono.Net.Security;
60
61 namespace System.Net.Mail {
62         [Obsolete ("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
63         public class SmtpClient
64         : IDisposable
65         {
66                 #region Fields
67
68                 string host;
69                 int port;
70                 int timeout = 100000;
71                 ICredentialsByHost credentials;
72                 string pickupDirectoryLocation;
73                 SmtpDeliveryMethod deliveryMethod;
74                 bool enableSsl;
75 #if SECURITY_DEP                
76                 X509CertificateCollection clientCertificates;
77 #endif          
78
79                 TcpClient client;
80                 Stream stream;
81                 StreamWriter writer;
82                 StreamReader reader;
83                 int boundaryIndex;
84                 MailAddress defaultFrom;
85
86                 MailMessage messageInProcess;
87
88                 BackgroundWorker worker;
89                 object user_async_state;
90
91                 [Flags]
92                 enum AuthMechs {
93                         None        = 0,
94                         Login       = 0x01,
95                         Plain       = 0x02,
96                 }
97
98                 class CancellationException : Exception
99                 {
100                 }
101
102                 AuthMechs authMechs;
103                 Mutex mutex = new Mutex ();
104
105                 #endregion // Fields
106
107                 #region Constructors
108
109                 public SmtpClient ()
110                         : this (null, 0)
111                 {
112                 }
113
114                 public SmtpClient (string host)
115                         : this (host, 0)
116                 {
117                 }
118
119                 public SmtpClient (string host, int port) {
120 #if CONFIGURATION_DEP
121                         SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
122
123                         if (cfg != null) {
124                                 this.host = cfg.Network.Host;
125                                 this.port = cfg.Network.Port;
126                                 this.enableSsl = cfg.Network.EnableSsl;
127                                 TargetName = cfg.Network.TargetName;
128                                 if (this.TargetName == null)
129                                         TargetName = "SMTPSVC/" + (host != null ? host : "");
130
131                                 
132                                 if (cfg.Network.UserName != null) {
133                                         string password = String.Empty;
134
135                                         if (cfg.Network.Password != null)
136                                                 password = cfg.Network.Password;
137
138                                         Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
139                                 }
140
141                                 if (!String.IsNullOrEmpty (cfg.From))
142                                         defaultFrom = new MailAddress (cfg.From);
143                         }
144 #else
145                         // Just to eliminate the warning, this codepath does not end up in production.
146                         defaultFrom = null;
147 #endif
148
149                         if (!String.IsNullOrEmpty (host))
150                                 this.host = host;
151
152                         if (port != 0)
153                                 this.port = port;
154                         else if (this.port == 0)
155                                 this.port = 25;
156                 }
157
158                 #endregion // Constructors
159
160                 #region Properties
161
162 #if SECURITY_DEP
163                 [MonoTODO("Client certificates not used")]
164                 public X509CertificateCollection ClientCertificates {
165                         get {
166                                 if (clientCertificates == null)
167                                         clientCertificates = new X509CertificateCollection ();
168                                 return clientCertificates;
169                         }
170                 }
171 #endif
172
173                 public
174                 string TargetName { get; set; }
175
176                 public ICredentialsByHost Credentials {
177                         get { return credentials; }
178                         set {
179                                 CheckState ();
180                                 credentials = value;
181                         }
182                 }
183
184                 public SmtpDeliveryMethod DeliveryMethod {
185                         get { return deliveryMethod; }
186                         set {
187                                 CheckState ();
188                                 deliveryMethod = value;
189                         }
190                 }
191
192                 public bool EnableSsl {
193                         get { return enableSsl; }
194                         set {
195                                 CheckState ();
196                                 enableSsl = value;
197                         }
198                 }
199
200                 public string Host {
201                         get { return host; }
202                         set {
203                                 if (value == null)
204                                         throw new ArgumentNullException ("value");
205                                 if (value.Length == 0)
206                                         throw new ArgumentException ("An empty string is not allowed.", "value");
207                                 CheckState ();
208                                 host = value;
209                         }
210                 }
211
212                 public string PickupDirectoryLocation {
213                         get { return pickupDirectoryLocation; }
214                         set { pickupDirectoryLocation = value; }
215                 }
216
217                 public int Port {
218                         get { return port; }
219                         set { 
220                                 if (value <= 0)
221                                         throw new ArgumentOutOfRangeException ("value");
222                                 CheckState ();
223                                 port = value;
224                         }
225                 }
226
227                 [MonoTODO]
228                 public ServicePoint ServicePoint {
229                         get { throw new NotImplementedException (); }
230                 }
231
232                 public int Timeout {
233                         get { return timeout; }
234                         set { 
235                                 if (value < 0)
236                                         throw new ArgumentOutOfRangeException ("value");
237                                 CheckState ();
238                                 timeout = value; 
239                         }
240                 }
241
242                 public bool UseDefaultCredentials {
243                         get { return false; }
244                         [MonoNotSupported ("no DefaultCredential support in Mono")]
245                         set {
246                                 if (value)
247                                         throw new NotImplementedException ("Default credentials are not supported");
248                                 CheckState ();
249                         }
250                 }
251
252                 #endregion // Properties
253
254                 #region Events 
255
256                 public event SendCompletedEventHandler SendCompleted;
257
258                 #endregion // Events 
259
260                 #region Methods
261                 public void Dispose ()
262                 {
263                         Dispose (true);
264                 }
265
266                 [MonoTODO ("Does nothing at the moment.")]
267                 protected virtual void Dispose (bool disposing)
268                 {
269                         // TODO: We should close all the connections and abort any async operations here
270                 }
271                 private void CheckState ()
272                 {
273                         if (messageInProcess != null)
274                                 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
275                 }
276                 
277                 private static string EncodeAddress(MailAddress address)
278                 {
279                         if (!String.IsNullOrEmpty (address.DisplayName)) {
280                                 string encodedDisplayName = MailMessage.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
281                                 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
282                         }
283                         return address.ToString ();
284                 }
285
286                 private static string EncodeAddresses(MailAddressCollection addresses)
287                 {
288                         StringBuilder sb = new StringBuilder();
289                         bool first = true;
290                         foreach (MailAddress address in addresses) {
291                                 if (!first) {
292                                         sb.Append(", ");
293                                 }
294                                 sb.Append(EncodeAddress(address));
295                                 first = false;
296                         }
297                         return sb.ToString();
298                 }
299
300                 private string EncodeSubjectRFC2047 (MailMessage message)
301                 {
302                         return MailMessage.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
303                 }
304
305                 private string EncodeBody (MailMessage message)
306                 {
307                         string body = message.Body;
308                         Encoding encoding = message.BodyEncoding;
309                         // RFC 2045 encoding
310                         switch (message.ContentTransferEncoding) {
311                         case TransferEncoding.SevenBit:
312                                 return body;
313                         case TransferEncoding.Base64:
314                                 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
315                         default:
316                                 return ToQuotedPrintable (body, encoding);
317                         }
318                 }
319
320                 private string EncodeBody (AlternateView av)
321                 {
322                         //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
323
324                         byte [] bytes = new byte [av.ContentStream.Length];
325                         av.ContentStream.Read (bytes, 0, bytes.Length);
326
327                         // RFC 2045 encoding
328                         switch (av.TransferEncoding) {
329                         case TransferEncoding.SevenBit:
330                                 return Encoding.ASCII.GetString (bytes);
331                         case TransferEncoding.Base64:
332                                 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
333                         default:
334                                 return ToQuotedPrintable (bytes);
335                         }
336                 }
337
338
339                 private void EndSection (string section)
340                 {
341                         SendData (String.Format ("--{0}--", section));
342                         SendData (string.Empty);
343                 }
344
345                 private string GenerateBoundary ()
346                 {
347                         string output = GenerateBoundary (boundaryIndex);
348                         boundaryIndex += 1;
349                         return output;
350                 }
351
352                 private static string GenerateBoundary (int index)
353                 {
354                         return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
355                 }
356
357                 private bool IsError (SmtpResponse status)
358                 {
359                         return ((int) status.StatusCode) >= 400;
360                 }
361
362                 protected void OnSendCompleted (AsyncCompletedEventArgs e)
363                 {
364                         try {
365                                 if (SendCompleted != null)
366                                         SendCompleted (this, e);
367                         } finally {
368                                 worker = null;
369                                 user_async_state = null;
370                         }
371                 }
372
373                 private void CheckCancellation ()
374                 {
375                         if (worker != null && worker.CancellationPending)
376                                 throw new CancellationException ();
377                 }
378
379                 private SmtpResponse Read () {
380                         byte [] buffer = new byte [512];
381                         int position = 0;
382                         bool lastLine = false;
383
384                         do {
385                                 CheckCancellation ();
386
387                                 int readLength = stream.Read (buffer, position, buffer.Length - position);
388                                 if (readLength > 0) {
389                                         int available = position + readLength - 1;
390                                         if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
391                                                 for (int index = available - 3; ; index--) {
392                                                         if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
393                                                                 lastLine = buffer [index + 4] == ' ';
394                                                                 break;
395                                                         }
396                                                 }
397
398                                         // move position
399                                         position += readLength;
400
401                                         // check if buffer is full
402                                         if (position == buffer.Length) {
403                                                 byte [] newBuffer = new byte [buffer.Length * 2];
404                                                 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
405                                                 buffer = newBuffer;
406                                         }
407                                 }
408                                 else {
409                                         break;
410                                 }
411                         } while (!lastLine);
412
413                         if (position > 0) {
414                                 Encoding encoding = new ASCIIEncoding ();
415
416                                 string line = encoding.GetString (buffer, 0, position - 1);
417
418                                 // parse the line to the lastResponse object
419                                 SmtpResponse response = SmtpResponse.Parse (line);
420
421                                 return response;
422                         } else {
423                                 throw new System.IO.IOException ("Connection closed");
424                         }
425                 }
426
427                 void ResetExtensions()
428                 {
429                         authMechs = AuthMechs.None;
430                 }
431
432                 void ParseExtensions (string extens)
433                 {
434                         string[] parts = extens.Split ('\n');
435
436                         foreach (string part in parts) {
437                                 if (part.Length < 4)
438                                         continue;
439
440                                 string start = part.Substring (4);
441                                 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
442                                         string[] options = start.Split (' ');
443                                         for (int k = 1; k < options.Length; k++) {
444                                                 string option = options[k].Trim();
445                                                 // GSSAPI, KERBEROS_V4, NTLM not supported
446                                                 switch (option) {
447                                                 /*
448                                                 case "CRAM-MD5":
449                                                         authMechs |= AuthMechs.CramMD5;
450                                                         break;
451                                                 case "DIGEST-MD5":
452                                                         authMechs |= AuthMechs.DigestMD5;
453                                                         break;
454                                                 */
455                                                 case "LOGIN":
456                                                         authMechs |= AuthMechs.Login;
457                                                         break;
458                                                 case "PLAIN":
459                                                         authMechs |= AuthMechs.Plain;
460                                                         break;
461                                                 }
462                                         }
463                                 }
464                         }
465                 }
466
467                 public void Send (MailMessage message)
468                 {
469                         if (message == null)
470                                 throw new ArgumentNullException ("message");
471
472                         if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
473                                 throw new InvalidOperationException ("The SMTP host was not specified");
474                         else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
475                                 throw new NotSupportedException("IIS delivery is not supported");
476
477                         if (port == 0)
478                                 port = 25;
479                         
480                         // Block while sending
481                         mutex.WaitOne ();
482                         try {
483                                 messageInProcess = message;
484                                 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
485                                         SendToFile (message);
486                                 else
487                                         SendInternal (message);
488                         } catch (CancellationException) {
489                                 // This exception is introduced for convenient cancellation process.
490                         } catch (SmtpException) {
491                                 throw;
492                         } catch (Exception ex) {
493                                 throw new SmtpException ("Message could not be sent.", ex);
494                         } finally {
495                                 // Release the mutex to allow other threads access
496                                 mutex.ReleaseMutex ();
497                                 messageInProcess = null;
498                         }
499                 }
500
501                 private void SendInternal (MailMessage message)
502                 {
503                         CheckCancellation ();
504
505                         try {
506                                 client = new TcpClient (host, port);
507                                 stream = client.GetStream ();
508                                 // FIXME: this StreamWriter creation is bogus.
509                                 // It expects as if a Stream were able to switch to SSL
510                                 // mode (such behavior is only in Mainsoft Socket API).
511                                 writer = new StreamWriter (stream);
512                                 reader = new StreamReader (stream);
513
514                                 SendCore (message);
515                         } finally {
516                                 if (writer != null)
517                                         writer.Close ();
518                                 if (reader != null)
519                                         reader.Close ();
520                                 if (stream != null)
521                                         stream.Close ();
522                                 if (client != null)
523                                         client.Close ();
524                         }
525                 }
526  
527                 // FIXME: simple implementation, could be brushed up.
528                 private void SendToFile (MailMessage message)
529                 {
530                         if (!Path.IsPathRooted (pickupDirectoryLocation))
531                                 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
532
533                         string filename = Path.Combine (pickupDirectoryLocation,
534                                 Guid.NewGuid() + ".eml");
535
536                         try {
537                                 writer = new StreamWriter(filename);
538
539                                 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
540                                 //        For all we know, defaultFrom may be the envelope sender
541                                 // For now, we are no worse than some versions of .NET
542                                 MailAddress from = message.From;
543                                 if (from == null)
544                                         from = defaultFrom;
545
546                                 string dt = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
547                                 // remove ':' from time zone offset (e.g. from "+01:00")
548                                 dt = dt.Remove(dt.Length - 3, 1);
549                                 SendHeader(HeaderName.Date, dt);
550
551                                 SendHeader (HeaderName.From, EncodeAddress(from));
552                                 SendHeader (HeaderName.To, EncodeAddresses(message.To));
553                                 if (message.CC.Count > 0)
554                                         SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
555                                 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
556
557                                 foreach (string s in message.Headers.AllKeys)
558                                         SendHeader (s, message.Headers [s]);
559
560                                 AddPriorityHeader (message);
561
562                                 boundaryIndex = 0;
563                                 if (message.Attachments.Count > 0)
564                                         SendWithAttachments (message);
565                                 else
566                                         SendWithoutAttachments (message, null, false);
567
568
569                         } finally {
570                                 if (writer != null) writer.Close(); writer = null;
571                         }
572                 }
573
574                 private void SendCore (MailMessage message)
575                 {
576                         SmtpResponse status;
577
578                         status = Read ();
579                         if (IsError (status))
580                                 throw new SmtpException (status.StatusCode, status.Description);
581
582                         // EHLO
583                         
584                         // FIXME: parse the list of extensions so we don't bother wasting
585                         // our time trying commands if they aren't supported.
586                         
587                         // get the host name (not fully qualified)
588                         string fqdn = Dns.GetHostName ();
589                         try {
590                                 // we'll try for the fully qualified name - ref: bug #33551
591                                 fqdn = Dns.GetHostEntry (fqdn).HostName;
592                         }
593                         catch (SocketException) {
594                                 // we could not resolve our name but will continue with the partial name
595                                 // IOW we won't fail to send email because of this - ref: bug #37246
596                         }
597                         status = SendCommand ("EHLO " + fqdn);
598                         
599                         if (IsError (status)) {
600                                 status = SendCommand ("HELO " + fqdn);
601                                 
602                                 if (IsError (status))
603                                         throw new SmtpException (status.StatusCode, status.Description);
604                         } else {
605                                 // Parse ESMTP extensions
606                                 string extens = status.Description;
607                                 
608                                 if (extens != null)
609                                         ParseExtensions (extens);
610                         }
611                         
612                         if (enableSsl) {
613                                 InitiateSecureConnection ();
614                                 ResetExtensions();
615                                 writer = new StreamWriter (stream);
616                                 reader = new StreamReader (stream);
617                                 status = SendCommand ("EHLO " + fqdn);
618                         
619                                 if (IsError (status)) {
620                                         status = SendCommand ("HELO " + fqdn);
621                                 
622                                         if (IsError (status))
623                                                 throw new SmtpException (status.StatusCode, status.Description);
624                                 } else {
625                                         // Parse ESMTP extensions
626                                         string extens = status.Description;
627                                         if (extens != null)
628                                                 ParseExtensions (extens);
629                                 }
630                         }
631                         
632                         if (authMechs != AuthMechs.None)
633                                 Authenticate ();
634
635                         // The envelope sender: use 'Sender:' in preference of 'From:'
636                         MailAddress sender = message.Sender;
637                         if (sender == null)
638                                 sender = message.From;
639                         if (sender == null)
640                                 sender = defaultFrom;
641                         
642                         // MAIL FROM:
643                         status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
644                         if (IsError (status)) {
645                                 throw new SmtpException (status.StatusCode, status.Description);
646                         }
647
648                         // Send RCPT TO: for all recipients
649                         List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
650
651                         for (int i = 0; i < message.To.Count; i ++) {
652                                 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
653                                 if (IsError (status)) 
654                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
655                         }
656                         for (int i = 0; i < message.CC.Count; i ++) {
657                                 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
658                                 if (IsError (status)) 
659                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
660                         }
661                         for (int i = 0; i < message.Bcc.Count; i ++) {
662                                 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
663                                 if (IsError (status)) 
664                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
665                         }
666
667                         if (sfre.Count >0)
668                                 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
669
670                         // DATA
671                         status = SendCommand ("DATA");
672                         if (IsError (status))
673                                 throw new SmtpException (status.StatusCode, status.Description);
674
675                         // Send message headers
676                         string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
677                         // remove ':' from time zone offset (e.g. from "+01:00")
678                         dt = dt.Remove (dt.Length - 3, 1);
679                         SendHeader (HeaderName.Date, dt);
680
681                         MailAddress from = message.From;
682                         if (from == null)
683                                 from = defaultFrom;
684
685                         SendHeader (HeaderName.From, EncodeAddress (from));
686                         SendHeader (HeaderName.To, EncodeAddresses (message.To));
687                         if (message.CC.Count > 0)
688                                 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
689                         SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
690
691                         string v = "normal";
692                                 
693                         switch (message.Priority){
694                         case MailPriority.Normal:
695                                 v = "normal";
696                                 break;
697                                 
698                         case MailPriority.Low:
699                                 v = "non-urgent";
700                                 break;
701                                 
702                         case MailPriority.High:
703                                 v = "urgent";
704                                 break;
705                         }
706                         SendHeader ("Priority", v);
707                         if (message.Sender != null)
708                                 SendHeader ("Sender", EncodeAddress (message.Sender));
709                         if (message.ReplyToList.Count > 0)
710                                 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
711
712                         foreach (string s in message.Headers.AllKeys)
713                                 SendHeader (s, MailMessage.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
714         
715                         AddPriorityHeader (message);
716
717                         boundaryIndex = 0;
718                         if (message.Attachments.Count > 0)
719                                 SendWithAttachments (message);
720                         else
721                                 SendWithoutAttachments (message, null, false);
722
723                         SendDot ();
724
725                         status = Read ();
726                         if (IsError (status))
727                                 throw new SmtpException (status.StatusCode, status.Description);
728
729                         try {
730                                 status = SendCommand ("QUIT");
731                         } catch (System.IO.IOException) {
732                                 // We excuse server for the rude connection closing as a response to QUIT
733                         }
734                 }
735
736                 public void Send (string from, string to, string subject, string body)
737                 {
738                         Send (new MailMessage (from, to, subject, body));
739                 }
740
741                 public Task SendMailAsync (MailMessage message)
742                 {
743                         var tcs = new TaskCompletionSource<object> ();
744                         SendCompletedEventHandler handler = null;
745                         handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
746                         SendCompleted += handler;
747                         SendAsync (message, tcs);
748                         return tcs.Task;
749                 }
750
751                 public Task SendMailAsync (string from, string recipients, string subject, string body)
752                 {
753                         return SendMailAsync (new MailMessage (from, recipients, subject, body));
754                 }
755
756                 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
757                 {
758                         if (source != e.UserState)
759                                 return;
760
761                         client.SendCompleted -= handler;
762
763                         if (e.Error != null) {
764                                 source.SetException (e.Error);
765                                 return;
766                         }
767
768                         if (e.Cancelled) {
769                                 source.SetCanceled ();
770                                 return;
771                         }
772
773                         source.SetResult (null);
774                 }
775
776                 private void SendDot()
777                 {
778                         writer.Write(".\r\n");
779                         writer.Flush();
780                 }
781
782                 private void SendData (string data)
783                 {
784                         if (String.IsNullOrEmpty (data)) {
785                                 writer.Write("\r\n");
786                                 writer.Flush();
787                                 return;
788                         }
789
790                         StringReader sr = new StringReader (data);
791                         string line;
792                         bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
793                         while ((line = sr.ReadLine ()) != null) {
794                                 CheckCancellation ();
795
796                                 if (escapeDots) {
797                                         if (line.Length > 0 && line[0] == '.') {
798                                                 line = "." + line;
799                                         }
800                                 }
801                                 writer.Write (line);
802                                 writer.Write ("\r\n");
803                         }
804                         writer.Flush ();
805                 }
806
807                 public void SendAsync (MailMessage message, object userToken)
808                 {
809                         if (worker != null)
810                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
811
812                         worker = new BackgroundWorker ();
813                         worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
814                                 try {
815                                         user_async_state = ea.Argument;
816                                         Send (message);
817                                 } catch (Exception ex) {
818                                         ea.Result = ex;
819                                         throw ex;
820                                 }
821                         };
822                         worker.WorkerSupportsCancellation = true;
823                         worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
824                                 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
825                                 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
826                         };
827                         worker.RunWorkerAsync (userToken);
828                 }
829
830                 public void SendAsync (string from, string to, string subject, string body, object userToken)
831                 {
832                         SendAsync (new MailMessage (from, to, subject, body), userToken);
833                 }
834
835                 public void SendAsyncCancel ()
836                 {
837                         if (worker == null)
838                                 throw new InvalidOperationException ("SendAsync operation is not in progress");
839                         worker.CancelAsync ();
840                 }
841
842                 private void AddPriorityHeader (MailMessage message) {
843                         switch (message.Priority) {
844                         case MailPriority.High:
845                                 SendHeader (HeaderName.Priority, "Urgent");
846                                 SendHeader (HeaderName.Importance, "high");
847                                 SendHeader (HeaderName.XPriority, "1");
848                                 break;
849                         case MailPriority.Low:
850                                 SendHeader (HeaderName.Priority, "Non-Urgent");
851                                 SendHeader (HeaderName.Importance, "low");
852                                 SendHeader (HeaderName.XPriority, "5");
853                                 break;
854                         }
855                 }
856
857                 private void SendSimpleBody (MailMessage message) {
858                         SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
859                         if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
860                                 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
861                         SendData (string.Empty);
862
863                         SendData (EncodeBody (message));
864                 }
865
866                 private void SendBodylessSingleAlternate (AlternateView av) {
867                         SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
868                         if (av.TransferEncoding != TransferEncoding.SevenBit)
869                                 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
870                         SendData (string.Empty);
871
872                         SendData (EncodeBody (av));
873                 }
874
875                 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
876                 {
877                         if (message.Body == null && message.AlternateViews.Count == 1)
878                                 SendBodylessSingleAlternate (message.AlternateViews [0]);
879                         else if (message.AlternateViews.Count > 0)
880                                 SendBodyWithAlternateViews (message, boundary, attachmentExists);
881                         else
882                                 SendSimpleBody (message);
883                 }
884
885
886                 private void SendWithAttachments (MailMessage message) {
887                         string boundary = GenerateBoundary ();
888
889                         // first "multipart/mixed"
890                         ContentType messageContentType = new ContentType ();
891                         messageContentType.Boundary = boundary;
892                         messageContentType.MediaType = "multipart/mixed";
893                         messageContentType.CharSet = null;
894
895                         SendHeader (HeaderName.ContentType, messageContentType.ToString ());
896                         SendData (String.Empty);
897
898                         // body section
899                         Attachment body = null;
900
901                         if (message.AlternateViews.Count > 0)
902                                 SendWithoutAttachments (message, boundary, true);
903                         else {
904                                 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
905                                 message.Attachments.Insert (0, body);
906                         }
907
908                         try {
909                                 SendAttachments (message, body, boundary);
910                         } finally {
911                                 if (body != null)
912                                         message.Attachments.Remove (body);
913                         }
914
915                         EndSection (boundary);
916                 }
917
918                 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
919                 {
920                         AlternateViewCollection alternateViews = message.AlternateViews;
921
922                         string inner_boundary = GenerateBoundary ();
923
924                         ContentType messageContentType = new ContentType ();
925                         messageContentType.Boundary = inner_boundary;
926                         messageContentType.MediaType = "multipart/alternative";
927
928                         if (!attachmentExists) {
929                                 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
930                                 SendData (String.Empty);
931                         }
932
933                         // body section
934                         AlternateView body = null;
935                         if (message.Body != null) {
936                                 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
937                                 alternateViews.Insert (0, body);
938                                 StartSection (boundary, messageContentType);
939                         }
940
941 try {
942                         // alternate view sections
943                         foreach (AlternateView av in alternateViews) {
944
945                                 string alt_boundary = null;
946                                 ContentType contentType;
947                                 if (av.LinkedResources.Count > 0) {
948                                         alt_boundary = GenerateBoundary ();
949                                         contentType = new ContentType ("multipart/related");
950                                         contentType.Boundary = alt_boundary;
951                                         
952                                         contentType.Parameters ["type"] = av.ContentType.ToString ();
953                                         StartSection (inner_boundary, contentType);
954                                         StartSection (alt_boundary, av.ContentType, av);
955                                 } else {
956                                         contentType = new ContentType (av.ContentType.ToString ());
957                                         StartSection (inner_boundary, contentType, av);
958                                 }
959
960                                 switch (av.TransferEncoding) {
961                                 case TransferEncoding.Base64:
962                                         byte [] content = new byte [av.ContentStream.Length];
963                                         av.ContentStream.Read (content, 0, content.Length);
964                                             SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
965                                         break;
966                                 case TransferEncoding.QuotedPrintable:
967                                         byte [] bytes = new byte [av.ContentStream.Length];
968                                         av.ContentStream.Read (bytes, 0, bytes.Length);
969                                         SendData (ToQuotedPrintable (bytes));
970                                         break;
971                                 case TransferEncoding.SevenBit:
972                                 case TransferEncoding.Unknown:
973                                         content = new byte [av.ContentStream.Length];
974                                         av.ContentStream.Read (content, 0, content.Length);
975                                         SendData (Encoding.ASCII.GetString (content));
976                                         break;
977                                 }
978
979                                 if (av.LinkedResources.Count > 0) {
980                                         SendLinkedResources (message, av.LinkedResources, alt_boundary);
981                                         EndSection (alt_boundary);
982                                 }
983
984                                 if (!attachmentExists)
985                                         SendData (string.Empty);
986                         }
987
988 } finally {
989                         if (body != null)
990                                 alternateViews.Remove (body);
991 }
992                         EndSection (inner_boundary);
993                 }
994
995                 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
996                 {
997                         foreach (LinkedResource lr in resources) {
998                                 StartSection (boundary, lr.ContentType, lr);
999
1000                                 switch (lr.TransferEncoding) {
1001                                 case TransferEncoding.Base64:
1002                                         byte [] content = new byte [lr.ContentStream.Length];
1003                                         lr.ContentStream.Read (content, 0, content.Length);
1004                                             SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1005                                         break;
1006                                 case TransferEncoding.QuotedPrintable:
1007                                         byte [] bytes = new byte [lr.ContentStream.Length];
1008                                         lr.ContentStream.Read (bytes, 0, bytes.Length);
1009                                         SendData (ToQuotedPrintable (bytes));
1010                                         break;
1011                                 case TransferEncoding.SevenBit:
1012                                 case TransferEncoding.Unknown:
1013                                         content = new byte [lr.ContentStream.Length];
1014                                         lr.ContentStream.Read (content, 0, content.Length);
1015                                         SendData (Encoding.ASCII.GetString (content));
1016                                         break;
1017                                 }
1018                         }
1019                 }
1020
1021                 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1022                         foreach (Attachment att in message.Attachments) {
1023                                 ContentType contentType = new ContentType (att.ContentType.ToString ());
1024                                 if (att.Name != null) {
1025                                         contentType.Name = att.Name;
1026                                         if (att.NameEncoding != null)
1027                                                 contentType.CharSet = att.NameEncoding.HeaderName;
1028                                         att.ContentDisposition.FileName = att.Name;
1029                                 }
1030                                 StartSection (boundary, contentType, att, att != body);
1031
1032                                 byte [] content = new byte [att.ContentStream.Length];
1033                                 att.ContentStream.Read (content, 0, content.Length);
1034                                 switch (att.TransferEncoding) {
1035                                 case TransferEncoding.Base64:
1036                                         SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1037                                         break;
1038                                 case TransferEncoding.QuotedPrintable:
1039                                         SendData (ToQuotedPrintable (content));
1040                                         break;
1041                                 case TransferEncoding.SevenBit:
1042                                 case TransferEncoding.Unknown:
1043                                         SendData (Encoding.ASCII.GetString (content));
1044                                         break;
1045                                 }
1046
1047                                 SendData (string.Empty);
1048                         }
1049                 }
1050
1051                 private SmtpResponse SendCommand (string command)
1052                 {
1053                         writer.Write (command);
1054                         // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1055                         writer.Write ("\r\n");
1056                         writer.Flush ();
1057                         return Read ();
1058                 }
1059
1060                 private void SendHeader (string name, string value)
1061                 {
1062                         SendData (String.Format ("{0}: {1}", name, value));
1063                 }
1064
1065                 private void StartSection (string section, ContentType sectionContentType)
1066                 {
1067                         SendData (String.Format ("--{0}", section));
1068                         SendHeader ("content-type", sectionContentType.ToString ());
1069                         SendData (string.Empty);
1070                 }
1071
1072                 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1073                 {
1074                         SendData (String.Format ("--{0}", section));
1075                         SendHeader ("content-type", sectionContentType.ToString ());
1076                         SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1077                         if (!string.IsNullOrEmpty (att.ContentId))
1078                                 SendHeader("content-ID", "<" + att.ContentId + ">");
1079                         SendData (string.Empty);
1080                 }
1081
1082                 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1083                         SendData (String.Format ("--{0}", section));
1084                         if (!string.IsNullOrEmpty (att.ContentId))
1085                                 SendHeader("content-ID", "<" + att.ContentId + ">");
1086                         SendHeader ("content-type", sectionContentType.ToString ());
1087                         SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1088                         if (sendDisposition)
1089                                 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1090                         SendData (string.Empty);
1091                 }
1092                 
1093                 // use proper encoding to escape input
1094                 private string ToQuotedPrintable (string input, Encoding enc)
1095                 {
1096                         byte [] bytes = enc.GetBytes (input);
1097                         return ToQuotedPrintable (bytes);
1098                 }
1099
1100                 private string ToQuotedPrintable (byte [] bytes)
1101                 {
1102                         StringWriter writer = new StringWriter ();
1103                         int charsInLine = 0;
1104                         int curLen;
1105                         StringBuilder sb = new StringBuilder("=", 3);
1106                         byte equalSign = (byte)'=';
1107                         char c = (char)0;
1108
1109                         foreach (byte i in bytes) {
1110                                 if (i > 127 || i == equalSign) {
1111                                         sb.Length = 1;
1112                                         sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1113                                         curLen = 3;
1114                                 } else {
1115                                         c = Convert.ToChar (i);
1116                                         if (c == '\r' || c == '\n') {
1117                                                 writer.Write (c);
1118                                                 charsInLine = 0;
1119                                                 continue;
1120                                         }
1121                                         curLen = 1;
1122                                 }
1123                                 
1124                                 charsInLine += curLen;
1125                                 if (charsInLine > 75) {
1126                                         writer.Write ("=\r\n");
1127                                         charsInLine = curLen;
1128                                 }
1129                                 if (curLen == 1)
1130                                         writer.Write (c);
1131                                 else
1132                                         writer.Write (sb.ToString ());
1133                         }
1134
1135                         return writer.ToString ();
1136                 }
1137                 private static string GetTransferEncodingName (TransferEncoding encoding)
1138                 {
1139                         switch (encoding) {
1140                         case TransferEncoding.QuotedPrintable:
1141                                 return "quoted-printable";
1142                         case TransferEncoding.SevenBit:
1143                                 return "7bit";
1144                         case TransferEncoding.Base64:
1145                                 return "base64";
1146                         }
1147                         return "unknown";
1148                 }
1149
1150                 private void InitiateSecureConnection () {
1151                         SmtpResponse response = SendCommand ("STARTTLS");
1152
1153                         if (IsError (response)) {
1154                                 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1155                         }
1156
1157 #if SECURITY_DEP
1158                         var tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
1159                         var settings = MSI.MonoTlsSettings.CopyDefaultSettings ();
1160                         settings.UseServicePointManagerCallback = true;
1161                         var sslStream = tlsProvider.CreateSslStream (stream, false, settings);
1162                         CheckCancellation ();
1163                         sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1164                         stream = sslStream.AuthenticatedStream;
1165
1166 #else
1167                         throw new SystemException ("You are using an incomplete System.dll build");
1168 #endif
1169                 }
1170                 
1171                 void Authenticate ()
1172                 {
1173                         string user = null, pass = null;
1174                         
1175                         if (UseDefaultCredentials) {
1176                                 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1177                                 pass =  CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1178                         } else if (Credentials != null) {
1179                                 user = Credentials.GetCredential (host, port, "smtp").UserName;
1180                                 pass = Credentials.GetCredential (host, port, "smtp").Password;
1181                         } else {
1182                                 return;
1183                         }
1184                         
1185                         Authenticate (user, pass);
1186                 }
1187
1188                 void CheckStatus (SmtpResponse status, int i)
1189                 {
1190                         if (((int) status.StatusCode) != i)
1191                                 throw new SmtpException (status.StatusCode, status.Description);
1192                 }
1193
1194                 void ThrowIfError (SmtpResponse status)
1195                 {
1196                         if (IsError (status))
1197                                 throw new SmtpException (status.StatusCode, status.Description);
1198                 }
1199
1200                 void Authenticate (string user, string password)
1201                 {
1202                         if (authMechs == AuthMechs.None)
1203                                 return;
1204
1205                         SmtpResponse status;
1206                         /*
1207                         if ((authMechs & AuthMechs.DigestMD5) != 0) {
1208                                 status = SendCommand ("AUTH DIGEST-MD5");
1209                                 CheckStatus (status, 334);
1210                                 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1211                                 Console.WriteLine ("CHALLENGE: {0}", challenge);
1212                                 DigestSession session = new DigestSession ();
1213                                 session.Parse (false, challenge);
1214                                 string response = session.Authenticate (this, user, password);
1215                                 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1216                                 CheckStatus (status, 235);
1217                         } else */
1218                         if ((authMechs & AuthMechs.Login) != 0) {
1219                                 status = SendCommand ("AUTH LOGIN");
1220                                 CheckStatus (status, 334);
1221                                 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1222                                 CheckStatus (status, 334);
1223                                 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1224                                 CheckStatus (status, 235);
1225                         } else if ((authMechs & AuthMechs.Plain) != 0) {
1226                                 string s = String.Format ("\0{0}\0{1}", user, password);
1227                                 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1228                                 status = SendCommand ("AUTH PLAIN " + s);
1229                                 CheckStatus (status, 235);
1230                         } else {
1231                                 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1232                         }
1233                 }
1234
1235                 #endregion // Methods
1236                 
1237                 // The HeaderName struct is used to store constant string values representing mail headers.
1238                 private struct HeaderName {
1239                         public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1240                         public const string ContentType = "Content-Type";
1241                         public const string Bcc = "Bcc";
1242                         public const string Cc = "Cc";
1243                         public const string From = "From";
1244                         public const string Subject = "Subject";
1245                         public const string To = "To";
1246                         public const string MimeVersion = "MIME-Version";
1247                         public const string MessageId = "Message-ID";
1248                         public const string Priority = "Priority";
1249                         public const string Importance = "Importance";
1250                         public const string XPriority = "X-Priority";
1251                         public const string Date = "Date";
1252                 }
1253
1254                 // This object encapsulates the status code and description of an SMTP response.
1255                 private struct SmtpResponse {
1256                         public SmtpStatusCode StatusCode;
1257                         public string Description;
1258
1259                         public static SmtpResponse Parse (string line) {
1260                                 SmtpResponse response = new SmtpResponse ();
1261
1262                                 if (line.Length < 4)
1263                                         throw new SmtpException ("Response is to short " +
1264                                                                  line.Length + ".");
1265
1266                                 if ((line [3] != ' ') && (line [3] != '-'))
1267                                         throw new SmtpException ("Response format is wrong.(" +
1268                                                                  line + ")");
1269
1270                                 // parse the response code
1271                                 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1272
1273                                 // set the raw response
1274                                 response.Description = line;
1275
1276                                 return response;
1277                         }
1278                 }
1279         }
1280
1281         class CCredentialsByHost : ICredentialsByHost
1282         {
1283                 public CCredentialsByHost (string userName, string password) {
1284                         this.userName = userName;
1285                         this.password = password;
1286                 }
1287
1288                 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1289                         return new NetworkCredential (userName, password);
1290                 }
1291
1292                 private string userName;
1293                 private string password;
1294         }
1295 }
1296