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