[bcl] Remove NET_4_0 defines from class libs.
[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
33 #if MONOTOUCH || MONODROID
34 using System.Security.Cryptography.X509Certificates;
35 #else
36 extern alias PrebuiltSystem;
37 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
38 using System.Security.Cryptography.X509Certificates;
39 #endif
40
41 #endif
42
43 using System;
44 using System.Collections.Generic;
45 using System.ComponentModel;
46 using System.Globalization;
47 using System.IO;
48 using System.Net;
49 using System.Net.Mime;
50 using System.Net.Sockets;
51 using System.Text;
52 using System.Threading;
53 using System.Reflection;
54 using System.Net.Configuration;
55 using System.Configuration;
56 using System.Net.Security;
57 using System.Security.Authentication;
58 #if NET_4_5
59 using System.Threading.Tasks;
60 #endif
61
62 namespace System.Net.Mail {
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 = ContentType.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 ContentType.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                         status = SendCommand ("EHLO " + Dns.GetHostName ());
587                         
588                         if (IsError (status)) {
589                                 status = SendCommand ("HELO " + Dns.GetHostName ());
590                                 
591                                 if (IsError (status))
592                                         throw new SmtpException (status.StatusCode, status.Description);
593                         } else {
594                                 // Parse ESMTP extensions
595                                 string extens = status.Description;
596                                 
597                                 if (extens != null)
598                                         ParseExtensions (extens);
599                         }
600                         
601                         if (enableSsl) {
602                                 InitiateSecureConnection ();
603                                 ResetExtensions();
604                                 writer = new StreamWriter (stream);
605                                 reader = new StreamReader (stream);
606                                 status = SendCommand ("EHLO " + Dns.GetHostName ());
607                         
608                                 if (IsError (status)) {
609                                         status = SendCommand ("HELO " + Dns.GetHostName ());
610                                 
611                                         if (IsError (status))
612                                                 throw new SmtpException (status.StatusCode, status.Description);
613                                 } else {
614                                         // Parse ESMTP extensions
615                                         string extens = status.Description;
616                                         if (extens != null)
617                                                 ParseExtensions (extens);
618                                 }
619                         }
620                         
621                         if (authMechs != AuthMechs.None)
622                                 Authenticate ();
623
624                         // The envelope sender: use 'Sender:' in preference of 'From:'
625                         MailAddress sender = message.Sender;
626                         if (sender == null)
627                                 sender = message.From;
628                         if (sender == null)
629                                 sender = defaultFrom;
630                         
631                         // MAIL FROM:
632                         status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
633                         if (IsError (status)) {
634                                 throw new SmtpException (status.StatusCode, status.Description);
635                         }
636
637                         // Send RCPT TO: for all recipients
638                         List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
639
640                         for (int i = 0; i < message.To.Count; i ++) {
641                                 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
642                                 if (IsError (status)) 
643                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
644                         }
645                         for (int i = 0; i < message.CC.Count; i ++) {
646                                 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
647                                 if (IsError (status)) 
648                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
649                         }
650                         for (int i = 0; i < message.Bcc.Count; i ++) {
651                                 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
652                                 if (IsError (status)) 
653                                         sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
654                         }
655
656                         if (sfre.Count >0)
657                                 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
658
659                         // DATA
660                         status = SendCommand ("DATA");
661                         if (IsError (status))
662                                 throw new SmtpException (status.StatusCode, status.Description);
663
664                         // Send message headers
665                         string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
666                         // remove ':' from time zone offset (e.g. from "+01:00")
667                         dt = dt.Remove (dt.Length - 3, 1);
668                         SendHeader (HeaderName.Date, dt);
669
670                         MailAddress from = message.From;
671                         if (from == null)
672                                 from = defaultFrom;
673
674                         SendHeader (HeaderName.From, EncodeAddress (from));
675                         SendHeader (HeaderName.To, EncodeAddresses (message.To));
676                         if (message.CC.Count > 0)
677                                 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
678                         SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
679
680                         string v = "normal";
681                                 
682                         switch (message.Priority){
683                         case MailPriority.Normal:
684                                 v = "normal";
685                                 break;
686                                 
687                         case MailPriority.Low:
688                                 v = "non-urgent";
689                                 break;
690                                 
691                         case MailPriority.High:
692                                 v = "urgent";
693                                 break;
694                         }
695                         SendHeader ("Priority", v);
696                         if (message.Sender != null)
697                                 SendHeader ("Sender", EncodeAddress (message.Sender));
698                         if (message.ReplyToList.Count > 0)
699                                 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
700
701                         foreach (string s in message.Headers.AllKeys)
702                                 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
703         
704                         AddPriorityHeader (message);
705
706                         boundaryIndex = 0;
707                         if (message.Attachments.Count > 0)
708                                 SendWithAttachments (message);
709                         else
710                                 SendWithoutAttachments (message, null, false);
711
712                         SendDot ();
713
714                         status = Read ();
715                         if (IsError (status))
716                                 throw new SmtpException (status.StatusCode, status.Description);
717
718                         try {
719                                 status = SendCommand ("QUIT");
720                         } catch (System.IO.IOException) {
721                                 // We excuse server for the rude connection closing as a response to QUIT
722                         }
723                 }
724
725                 public void Send (string from, string to, string subject, string body)
726                 {
727                         Send (new MailMessage (from, to, subject, body));
728                 }
729
730 #if NET_4_5
731                 public Task SendMailAsync (MailMessage message)
732                 {
733                         var tcs = new TaskCompletionSource<object> ();
734                         SendCompletedEventHandler handler = null;
735                         handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
736                         SendCompleted += handler;
737                         SendAsync (message, tcs);
738                         return tcs.Task;
739                 }
740
741                 public Task SendMailAsync (string from, string recipients, string subject, string body)
742                 {
743                         return SendMailAsync (new MailMessage (from, recipients, subject, body));
744                 }
745
746                 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
747                 {
748                         if ((object) handler != e.UserState)
749                                 return;
750
751                         client.SendCompleted -= handler;
752
753                         if (e.Error != null) {
754                                 source.SetException (e.Error);
755                                 return;
756                         }
757
758                         if (e.Cancelled) {
759                                 source.SetCanceled ();
760                                 return;
761                         }
762
763                         source.SetResult (null);
764                 }
765 #endif
766
767                 private void SendDot()
768                 {
769                         writer.Write(".\r\n");
770                         writer.Flush();
771                 }
772
773                 private void SendData (string data)
774                 {
775                         if (String.IsNullOrEmpty (data)) {
776                                 writer.Write("\r\n");
777                                 writer.Flush();
778                                 return;
779                         }
780
781                         StringReader sr = new StringReader (data);
782                         string line;
783                         bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
784                         while ((line = sr.ReadLine ()) != null) {
785                                 CheckCancellation ();
786
787                                 if (escapeDots) {
788                                         int i;
789                                         for (i = 0; i < line.Length; i++) {
790                                                 if (line[i] != '.')
791                                                         break;
792                                         }
793                                         if (i > 0 && i == line.Length) {
794                                                 line += ".";
795                                         }
796                                 }
797                                 writer.Write (line);
798                                 writer.Write ("\r\n");
799                         }
800                         writer.Flush ();
801                 }
802
803                 public void SendAsync (MailMessage message, object userToken)
804                 {
805                         if (worker != null)
806                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
807
808                         worker = new BackgroundWorker ();
809                         worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
810                                 try {
811                                         user_async_state = ea.Argument;
812                                         Send (message);
813                                 } catch (Exception ex) {
814                                         ea.Result = ex;
815                                         throw ex;
816                                 }
817                         };
818                         worker.WorkerSupportsCancellation = true;
819                         worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
820                                 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
821                                 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
822                         };
823                         worker.RunWorkerAsync (userToken);
824                 }
825
826                 public void SendAsync (string from, string to, string subject, string body, object userToken)
827                 {
828                         SendAsync (new MailMessage (from, to, subject, body), userToken);
829                 }
830
831                 public void SendAsyncCancel ()
832                 {
833                         if (worker == null)
834                                 throw new InvalidOperationException ("SendAsync operation is not in progress");
835                         worker.CancelAsync ();
836                 }
837
838                 private void AddPriorityHeader (MailMessage message) {
839                         switch (message.Priority) {
840                         case MailPriority.High:
841                                 SendHeader (HeaderName.Priority, "Urgent");
842                                 SendHeader (HeaderName.Importance, "high");
843                                 SendHeader (HeaderName.XPriority, "1");
844                                 break;
845                         case MailPriority.Low:
846                                 SendHeader (HeaderName.Priority, "Non-Urgent");
847                                 SendHeader (HeaderName.Importance, "low");
848                                 SendHeader (HeaderName.XPriority, "5");
849                                 break;
850                         }
851                 }
852
853                 private void SendSimpleBody (MailMessage message) {
854                         SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
855                         if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
856                                 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
857                         SendData (string.Empty);
858
859                         SendData (EncodeBody (message));
860                 }
861
862                 private void SendBodylessSingleAlternate (AlternateView av) {
863                         SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
864                         if (av.TransferEncoding != TransferEncoding.SevenBit)
865                                 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
866                         SendData (string.Empty);
867
868                         SendData (EncodeBody (av));
869                 }
870
871                 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
872                 {
873                         if (message.Body == null && message.AlternateViews.Count == 1)
874                                 SendBodylessSingleAlternate (message.AlternateViews [0]);
875                         else if (message.AlternateViews.Count > 0)
876                                 SendBodyWithAlternateViews (message, boundary, attachmentExists);
877                         else
878                                 SendSimpleBody (message);
879                 }
880
881
882                 private void SendWithAttachments (MailMessage message) {
883                         string boundary = GenerateBoundary ();
884
885                         // first "multipart/mixed"
886                         ContentType messageContentType = new ContentType ();
887                         messageContentType.Boundary = boundary;
888                         messageContentType.MediaType = "multipart/mixed";
889                         messageContentType.CharSet = null;
890
891                         SendHeader (HeaderName.ContentType, messageContentType.ToString ());
892                         SendData (String.Empty);
893
894                         // body section
895                         Attachment body = null;
896
897                         if (message.AlternateViews.Count > 0)
898                                 SendWithoutAttachments (message, boundary, true);
899                         else {
900                                 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
901                                 message.Attachments.Insert (0, body);
902                         }
903
904                         try {
905                                 SendAttachments (message, body, boundary);
906                         } finally {
907                                 if (body != null)
908                                         message.Attachments.Remove (body);
909                         }
910
911                         EndSection (boundary);
912                 }
913
914                 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
915                 {
916                         AlternateViewCollection alternateViews = message.AlternateViews;
917
918                         string inner_boundary = GenerateBoundary ();
919
920                         ContentType messageContentType = new ContentType ();
921                         messageContentType.Boundary = inner_boundary;
922                         messageContentType.MediaType = "multipart/alternative";
923
924                         if (!attachmentExists) {
925                                 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
926                                 SendData (String.Empty);
927                         }
928
929                         // body section
930                         AlternateView body = null;
931                         if (message.Body != null) {
932                                 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
933                                 alternateViews.Insert (0, body);
934                                 StartSection (boundary, messageContentType);
935                         }
936
937 try {
938                         // alternate view sections
939                         foreach (AlternateView av in alternateViews) {
940
941                                 string alt_boundary = null;
942                                 ContentType contentType;
943                                 if (av.LinkedResources.Count > 0) {
944                                         alt_boundary = GenerateBoundary ();
945                                         contentType = new ContentType ("multipart/related");
946                                         contentType.Boundary = alt_boundary;
947                                         
948                                         contentType.Parameters ["type"] = av.ContentType.ToString ();
949                                         StartSection (inner_boundary, contentType);
950                                         StartSection (alt_boundary, av.ContentType, av);
951                                 } else {
952                                         contentType = new ContentType (av.ContentType.ToString ());
953                                         StartSection (inner_boundary, contentType, av);
954                                 }
955
956                                 switch (av.TransferEncoding) {
957                                 case TransferEncoding.Base64:
958                                         byte [] content = new byte [av.ContentStream.Length];
959                                         av.ContentStream.Read (content, 0, content.Length);
960                                             SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
961                                         break;
962                                 case TransferEncoding.QuotedPrintable:
963                                         byte [] bytes = new byte [av.ContentStream.Length];
964                                         av.ContentStream.Read (bytes, 0, bytes.Length);
965                                         SendData (ToQuotedPrintable (bytes));
966                                         break;
967                                 case TransferEncoding.SevenBit:
968                                 case TransferEncoding.Unknown:
969                                         content = new byte [av.ContentStream.Length];
970                                         av.ContentStream.Read (content, 0, content.Length);
971                                         SendData (Encoding.ASCII.GetString (content));
972                                         break;
973                                 }
974
975                                 if (av.LinkedResources.Count > 0) {
976                                         SendLinkedResources (message, av.LinkedResources, alt_boundary);
977                                         EndSection (alt_boundary);
978                                 }
979
980                                 if (!attachmentExists)
981                                         SendData (string.Empty);
982                         }
983
984 } finally {
985                         if (body != null)
986                                 alternateViews.Remove (body);
987 }
988                         EndSection (inner_boundary);
989                 }
990
991                 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
992                 {
993                         foreach (LinkedResource lr in resources) {
994                                 StartSection (boundary, lr.ContentType, lr);
995
996                                 switch (lr.TransferEncoding) {
997                                 case TransferEncoding.Base64:
998                                         byte [] content = new byte [lr.ContentStream.Length];
999                                         lr.ContentStream.Read (content, 0, content.Length);
1000                                             SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1001                                         break;
1002                                 case TransferEncoding.QuotedPrintable:
1003                                         byte [] bytes = new byte [lr.ContentStream.Length];
1004                                         lr.ContentStream.Read (bytes, 0, bytes.Length);
1005                                         SendData (ToQuotedPrintable (bytes));
1006                                         break;
1007                                 case TransferEncoding.SevenBit:
1008                                 case TransferEncoding.Unknown:
1009                                         content = new byte [lr.ContentStream.Length];
1010                                         lr.ContentStream.Read (content, 0, content.Length);
1011                                         SendData (Encoding.ASCII.GetString (content));
1012                                         break;
1013                                 }
1014                         }
1015                 }
1016
1017                 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1018                         foreach (Attachment att in message.Attachments) {
1019                                 ContentType contentType = new ContentType (att.ContentType.ToString ());
1020                                 if (att.Name != null) {
1021                                         contentType.Name = att.Name;
1022                                         if (att.NameEncoding != null)
1023                                                 contentType.CharSet = att.NameEncoding.HeaderName;
1024                                         att.ContentDisposition.FileName = att.Name;
1025                                 }
1026                                 StartSection (boundary, contentType, att, att != body);
1027
1028                                 byte [] content = new byte [att.ContentStream.Length];
1029                                 att.ContentStream.Read (content, 0, content.Length);
1030                                 switch (att.TransferEncoding) {
1031                                 case TransferEncoding.Base64:
1032                                         SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1033                                         break;
1034                                 case TransferEncoding.QuotedPrintable:
1035                                         SendData (ToQuotedPrintable (content));
1036                                         break;
1037                                 case TransferEncoding.SevenBit:
1038                                 case TransferEncoding.Unknown:
1039                                         SendData (Encoding.ASCII.GetString (content));
1040                                         break;
1041                                 }
1042
1043                                 SendData (string.Empty);
1044                         }
1045                 }
1046
1047                 private SmtpResponse SendCommand (string command)
1048                 {
1049                         writer.Write (command);
1050                         // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1051                         writer.Write ("\r\n");
1052                         writer.Flush ();
1053                         return Read ();
1054                 }
1055
1056                 private void SendHeader (string name, string value)
1057                 {
1058                         SendData (String.Format ("{0}: {1}", name, value));
1059                 }
1060
1061                 private void StartSection (string section, ContentType sectionContentType)
1062                 {
1063                         SendData (String.Format ("--{0}", section));
1064                         SendHeader ("content-type", sectionContentType.ToString ());
1065                         SendData (string.Empty);
1066                 }
1067
1068                 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1069                 {
1070                         SendData (String.Format ("--{0}", section));
1071                         SendHeader ("content-type", sectionContentType.ToString ());
1072                         SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1073                         if (!string.IsNullOrEmpty (att.ContentId))
1074                                 SendHeader("content-ID", "<" + att.ContentId + ">");
1075                         SendData (string.Empty);
1076                 }
1077
1078                 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1079                         SendData (String.Format ("--{0}", section));
1080                         if (!string.IsNullOrEmpty (att.ContentId))
1081                                 SendHeader("content-ID", "<" + att.ContentId + ">");
1082                         SendHeader ("content-type", sectionContentType.ToString ());
1083                         SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1084                         if (sendDisposition)
1085                                 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1086                         SendData (string.Empty);
1087                 }
1088                 
1089                 // use proper encoding to escape input
1090                 private string ToQuotedPrintable (string input, Encoding enc)
1091                 {
1092                         byte [] bytes = enc.GetBytes (input);
1093                         return ToQuotedPrintable (bytes);
1094                 }
1095
1096                 private string ToQuotedPrintable (byte [] bytes)
1097                 {
1098                         StringWriter writer = new StringWriter ();
1099                         int charsInLine = 0;
1100                         int curLen;
1101                         StringBuilder sb = new StringBuilder("=", 3);
1102                         byte equalSign = (byte)'=';
1103                         char c = (char)0;
1104
1105                         foreach (byte i in bytes) {
1106                                 if (i > 127 || i == equalSign) {
1107                                         sb.Length = 1;
1108                                         sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1109                                         curLen = 3;
1110                                 } else {
1111                                         c = Convert.ToChar (i);
1112                                         if (c == '\r' || c == '\n') {
1113                                                 writer.Write (c);
1114                                                 charsInLine = 0;
1115                                                 continue;
1116                                         }
1117                                         curLen = 1;
1118                                 }
1119                                 
1120                                 charsInLine += curLen;
1121                                 if (charsInLine > 75) {
1122                                         writer.Write ("=\r\n");
1123                                         charsInLine = curLen;
1124                                 }
1125                                 if (curLen == 1)
1126                                         writer.Write (c);
1127                                 else
1128                                         writer.Write (sb.ToString ());
1129                         }
1130
1131                         return writer.ToString ();
1132                 }
1133                 private static string GetTransferEncodingName (TransferEncoding encoding)
1134                 {
1135                         switch (encoding) {
1136                         case TransferEncoding.QuotedPrintable:
1137                                 return "quoted-printable";
1138                         case TransferEncoding.SevenBit:
1139                                 return "7bit";
1140                         case TransferEncoding.Base64:
1141                                 return "base64";
1142                         }
1143                         return "unknown";
1144                 }
1145
1146 #if SECURITY_DEP
1147                 RemoteCertificateValidationCallback callback = delegate (object sender,
1148                                                                          X509Certificate certificate,
1149                                                                          X509Chain chain,
1150                                                                          SslPolicyErrors sslPolicyErrors) {
1151                         // honor any exciting callback defined on ServicePointManager
1152                         if (ServicePointManager.ServerCertificateValidationCallback != null)
1153                                 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1154                         // otherwise provide our own
1155                         if (sslPolicyErrors != SslPolicyErrors.None)
1156                                 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1157                         return true;
1158                         };
1159 #endif
1160
1161                 private void InitiateSecureConnection () {
1162                         SmtpResponse response = SendCommand ("STARTTLS");
1163
1164                         if (IsError (response)) {
1165                                 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1166                         }
1167
1168 #if   SECURITY_DEP
1169                         SslStream sslStream = new SslStream (stream, false, callback, null);
1170                         CheckCancellation ();
1171                         sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1172                         stream = sslStream;
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