2 // System.Net.Mail.SmtpClient.cs
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2004
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
33 #if MONOTOUCH || MONODROID
34 using System.Security.Cryptography.X509Certificates;
36 extern alias PrebuiltSystem;
37 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
38 using System.Security.Cryptography.X509Certificates;
44 using System.Collections.Generic;
45 using System.ComponentModel;
46 using System.Globalization;
49 using System.Net.Mime;
50 using System.Net.Sockets;
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;
59 using System.Threading.Tasks;
62 namespace System.Net.Mail {
63 public class SmtpClient
71 ICredentialsByHost credentials;
72 string pickupDirectoryLocation;
73 SmtpDeliveryMethod deliveryMethod;
76 X509CertificateCollection clientCertificates;
84 MailAddress defaultFrom;
86 MailMessage messageInProcess;
88 BackgroundWorker worker;
89 object user_async_state;
98 class CancellationException : Exception
103 Mutex mutex = new Mutex ();
114 public SmtpClient (string host)
119 public SmtpClient (string host, int port) {
120 #if CONFIGURATION_DEP
121 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
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 : "");
132 if (cfg.Network.UserName != null) {
133 string password = String.Empty;
135 if (cfg.Network.Password != null)
136 password = cfg.Network.Password;
138 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
141 if (!String.IsNullOrEmpty (cfg.From))
142 defaultFrom = new MailAddress (cfg.From);
145 // Just to eliminate the warning, this codepath does not end up in production.
149 if (!String.IsNullOrEmpty (host))
154 else if (this.port == 0)
158 #endregion // Constructors
163 [MonoTODO("Client certificates not used")]
164 public X509CertificateCollection ClientCertificates {
166 if (clientCertificates == null)
167 clientCertificates = new X509CertificateCollection ();
168 return clientCertificates;
174 string TargetName { get; set; }
176 public ICredentialsByHost Credentials {
177 get { return credentials; }
184 public SmtpDeliveryMethod DeliveryMethod {
185 get { return deliveryMethod; }
188 deliveryMethod = value;
192 public bool EnableSsl {
193 get { return enableSsl; }
204 throw new ArgumentNullException ("value");
205 if (value.Length == 0)
206 throw new ArgumentException ("An empty string is not allowed.", "value");
212 public string PickupDirectoryLocation {
213 get { return pickupDirectoryLocation; }
214 set { pickupDirectoryLocation = value; }
221 throw new ArgumentOutOfRangeException ("value");
228 public ServicePoint ServicePoint {
229 get { throw new NotImplementedException (); }
233 get { return timeout; }
236 throw new ArgumentOutOfRangeException ("value");
242 public bool UseDefaultCredentials {
243 get { return false; }
244 [MonoNotSupported ("no DefaultCredential support in Mono")]
247 throw new NotImplementedException ("Default credentials are not supported");
252 #endregion // Properties
256 public event SendCompletedEventHandler SendCompleted;
261 public void Dispose ()
266 [MonoTODO ("Does nothing at the moment.")]
267 protected virtual void Dispose (bool disposing)
269 // TODO: We should close all the connections and abort any async operations here
271 private void CheckState ()
273 if (messageInProcess != null)
274 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
277 private static string EncodeAddress(MailAddress address)
279 if (!String.IsNullOrEmpty (address.DisplayName)) {
280 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
281 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
283 return address.ToString ();
286 private static string EncodeAddresses(MailAddressCollection addresses)
288 StringBuilder sb = new StringBuilder();
290 foreach (MailAddress address in addresses) {
294 sb.Append(EncodeAddress(address));
297 return sb.ToString();
300 private string EncodeSubjectRFC2047 (MailMessage message)
302 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
305 private string EncodeBody (MailMessage message)
307 string body = message.Body;
308 Encoding encoding = message.BodyEncoding;
310 switch (message.ContentTransferEncoding) {
311 case TransferEncoding.SevenBit:
313 case TransferEncoding.Base64:
314 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
316 return ToQuotedPrintable (body, encoding);
320 private string EncodeBody (AlternateView av)
322 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
324 byte [] bytes = new byte [av.ContentStream.Length];
325 av.ContentStream.Read (bytes, 0, bytes.Length);
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);
334 return ToQuotedPrintable (bytes);
339 private void EndSection (string section)
341 SendData (String.Format ("--{0}--", section));
342 SendData (string.Empty);
345 private string GenerateBoundary ()
347 string output = GenerateBoundary (boundaryIndex);
352 private static string GenerateBoundary (int index)
354 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
357 private bool IsError (SmtpResponse status)
359 return ((int) status.StatusCode) >= 400;
362 protected void OnSendCompleted (AsyncCompletedEventArgs e)
365 if (SendCompleted != null)
366 SendCompleted (this, e);
369 user_async_state = null;
373 private void CheckCancellation ()
375 if (worker != null && worker.CancellationPending)
376 throw new CancellationException ();
379 private SmtpResponse Read () {
380 byte [] buffer = new byte [512];
382 bool lastLine = false;
385 CheckCancellation ();
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] == ' ';
399 position += readLength;
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);
414 Encoding encoding = new ASCIIEncoding ();
416 string line = encoding.GetString (buffer, 0, position - 1);
418 // parse the line to the lastResponse object
419 SmtpResponse response = SmtpResponse.Parse (line);
423 throw new System.IO.IOException ("Connection closed");
427 void ResetExtensions()
429 authMechs = AuthMechs.None;
432 void ParseExtensions (string extens)
434 string[] parts = extens.Split ('\n');
436 foreach (string part in parts) {
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
449 authMechs |= AuthMechs.CramMD5;
452 authMechs |= AuthMechs.DigestMD5;
456 authMechs |= AuthMechs.Login;
459 authMechs |= AuthMechs.Plain;
467 public void Send (MailMessage message)
470 throw new ArgumentNullException ("message");
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");
480 // Block while sending
483 messageInProcess = message;
484 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
485 SendToFile (message);
487 SendInternal (message);
488 } catch (CancellationException) {
489 // This exception is introduced for convenient cancellation process.
490 } catch (SmtpException) {
492 } catch (Exception ex) {
493 throw new SmtpException ("Message could not be sent.", ex);
495 // Release the mutex to allow other threads access
496 mutex.ReleaseMutex ();
497 messageInProcess = null;
501 private void SendInternal (MailMessage message)
503 CheckCancellation ();
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);
527 // FIXME: simple implementation, could be brushed up.
528 private void SendToFile (MailMessage message)
530 if (!Path.IsPathRooted (pickupDirectoryLocation))
531 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
533 string filename = Path.Combine (pickupDirectoryLocation,
534 Guid.NewGuid() + ".eml");
537 writer = new StreamWriter(filename);
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;
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);
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));
557 foreach (string s in message.Headers.AllKeys)
558 SendHeader (s, message.Headers [s]);
560 AddPriorityHeader (message);
563 if (message.Attachments.Count > 0)
564 SendWithAttachments (message);
566 SendWithoutAttachments (message, null, false);
570 if (writer != null) writer.Close(); writer = null;
574 private void SendCore (MailMessage message)
579 if (IsError (status))
580 throw new SmtpException (status.StatusCode, status.Description);
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 ());
588 if (IsError (status)) {
589 status = SendCommand ("HELO " + Dns.GetHostName ());
591 if (IsError (status))
592 throw new SmtpException (status.StatusCode, status.Description);
594 // Parse ESMTP extensions
595 string extens = status.Description;
598 ParseExtensions (extens);
602 InitiateSecureConnection ();
604 writer = new StreamWriter (stream);
605 reader = new StreamReader (stream);
606 status = SendCommand ("EHLO " + Dns.GetHostName ());
608 if (IsError (status)) {
609 status = SendCommand ("HELO " + Dns.GetHostName ());
611 if (IsError (status))
612 throw new SmtpException (status.StatusCode, status.Description);
614 // Parse ESMTP extensions
615 string extens = status.Description;
617 ParseExtensions (extens);
621 if (authMechs != AuthMechs.None)
624 // The envelope sender: use 'Sender:' in preference of 'From:'
625 MailAddress sender = message.Sender;
627 sender = message.From;
629 sender = defaultFrom;
632 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
633 if (IsError (status)) {
634 throw new SmtpException (status.StatusCode, status.Description);
637 // Send RCPT TO: for all recipients
638 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
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));
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));
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));
657 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
660 status = SendCommand ("DATA");
661 if (IsError (status))
662 throw new SmtpException (status.StatusCode, status.Description);
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);
670 MailAddress from = message.From;
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));
682 switch (message.Priority){
683 case MailPriority.Normal:
687 case MailPriority.Low:
691 case MailPriority.High:
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));
701 foreach (string s in message.Headers.AllKeys)
702 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
704 AddPriorityHeader (message);
707 if (message.Attachments.Count > 0)
708 SendWithAttachments (message);
710 SendWithoutAttachments (message, null, false);
715 if (IsError (status))
716 throw new SmtpException (status.StatusCode, status.Description);
719 status = SendCommand ("QUIT");
720 } catch (System.IO.IOException) {
721 // We excuse server for the rude connection closing as a response to QUIT
725 public void Send (string from, string to, string subject, string body)
727 Send (new MailMessage (from, to, subject, body));
731 public Task SendMailAsync (MailMessage message)
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);
741 public Task SendMailAsync (string from, string recipients, string subject, string body)
743 return SendMailAsync (new MailMessage (from, recipients, subject, body));
746 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
748 if ((object) handler != e.UserState)
751 client.SendCompleted -= handler;
753 if (e.Error != null) {
754 source.SetException (e.Error);
759 source.SetCanceled ();
763 source.SetResult (null);
767 private void SendDot()
769 writer.Write(".\r\n");
773 private void SendData (string data)
775 if (String.IsNullOrEmpty (data)) {
776 writer.Write("\r\n");
781 StringReader sr = new StringReader (data);
783 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
784 while ((line = sr.ReadLine ()) != null) {
785 CheckCancellation ();
789 for (i = 0; i < line.Length; i++) {
793 if (i > 0 && i == line.Length) {
798 writer.Write ("\r\n");
803 public void SendAsync (MailMessage message, object userToken)
806 throw new InvalidOperationException ("Another SendAsync operation is in progress");
808 worker = new BackgroundWorker ();
809 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
811 user_async_state = ea.Argument;
813 } catch (Exception ex) {
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));
823 worker.RunWorkerAsync (userToken);
826 public void SendAsync (string from, string to, string subject, string body, object userToken)
828 SendAsync (new MailMessage (from, to, subject, body), userToken);
831 public void SendAsyncCancel ()
834 throw new InvalidOperationException ("SendAsync operation is not in progress");
835 worker.CancelAsync ();
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");
845 case MailPriority.Low:
846 SendHeader (HeaderName.Priority, "Non-Urgent");
847 SendHeader (HeaderName.Importance, "low");
848 SendHeader (HeaderName.XPriority, "5");
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);
859 SendData (EncodeBody (message));
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);
868 SendData (EncodeBody (av));
871 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
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);
878 SendSimpleBody (message);
882 private void SendWithAttachments (MailMessage message) {
883 string boundary = GenerateBoundary ();
885 // first "multipart/mixed"
886 ContentType messageContentType = new ContentType ();
887 messageContentType.Boundary = boundary;
888 messageContentType.MediaType = "multipart/mixed";
889 messageContentType.CharSet = null;
891 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
892 SendData (String.Empty);
895 Attachment body = null;
897 if (message.AlternateViews.Count > 0)
898 SendWithoutAttachments (message, boundary, true);
900 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
901 message.Attachments.Insert (0, body);
905 SendAttachments (message, body, boundary);
908 message.Attachments.Remove (body);
911 EndSection (boundary);
914 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
916 AlternateViewCollection alternateViews = message.AlternateViews;
918 string inner_boundary = GenerateBoundary ();
920 ContentType messageContentType = new ContentType ();
921 messageContentType.Boundary = inner_boundary;
922 messageContentType.MediaType = "multipart/alternative";
924 if (!attachmentExists) {
925 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
926 SendData (String.Empty);
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);
938 // alternate view sections
939 foreach (AlternateView av in alternateViews) {
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;
948 contentType.Parameters ["type"] = av.ContentType.ToString ();
949 StartSection (inner_boundary, contentType);
950 StartSection (alt_boundary, av.ContentType, av);
952 contentType = new ContentType (av.ContentType.ToString ());
953 StartSection (inner_boundary, contentType, av);
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));
962 case TransferEncoding.QuotedPrintable:
963 byte [] bytes = new byte [av.ContentStream.Length];
964 av.ContentStream.Read (bytes, 0, bytes.Length);
965 SendData (ToQuotedPrintable (bytes));
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));
975 if (av.LinkedResources.Count > 0) {
976 SendLinkedResources (message, av.LinkedResources, alt_boundary);
977 EndSection (alt_boundary);
980 if (!attachmentExists)
981 SendData (string.Empty);
986 alternateViews.Remove (body);
988 EndSection (inner_boundary);
991 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
993 foreach (LinkedResource lr in resources) {
994 StartSection (boundary, lr.ContentType, lr);
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));
1002 case TransferEncoding.QuotedPrintable:
1003 byte [] bytes = new byte [lr.ContentStream.Length];
1004 lr.ContentStream.Read (bytes, 0, bytes.Length);
1005 SendData (ToQuotedPrintable (bytes));
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));
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;
1026 StartSection (boundary, contentType, att, att != body);
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));
1034 case TransferEncoding.QuotedPrintable:
1035 SendData (ToQuotedPrintable (content));
1037 case TransferEncoding.SevenBit:
1038 case TransferEncoding.Unknown:
1039 SendData (Encoding.ASCII.GetString (content));
1043 SendData (string.Empty);
1047 private SmtpResponse SendCommand (string command)
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");
1056 private void SendHeader (string name, string value)
1058 SendData (String.Format ("{0}: {1}", name, value));
1061 private void StartSection (string section, ContentType sectionContentType)
1063 SendData (String.Format ("--{0}", section));
1064 SendHeader ("content-type", sectionContentType.ToString ());
1065 SendData (string.Empty);
1068 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
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);
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);
1089 // use proper encoding to escape input
1090 private string ToQuotedPrintable (string input, Encoding enc)
1092 byte [] bytes = enc.GetBytes (input);
1093 return ToQuotedPrintable (bytes);
1096 private string ToQuotedPrintable (byte [] bytes)
1098 StringWriter writer = new StringWriter ();
1099 int charsInLine = 0;
1101 StringBuilder sb = new StringBuilder("=", 3);
1102 byte equalSign = (byte)'=';
1105 foreach (byte i in bytes) {
1106 if (i > 127 || i == equalSign) {
1108 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1111 c = Convert.ToChar (i);
1112 if (c == '\r' || c == '\n') {
1120 charsInLine += curLen;
1121 if (charsInLine > 75) {
1122 writer.Write ("=\r\n");
1123 charsInLine = curLen;
1128 writer.Write (sb.ToString ());
1131 return writer.ToString ();
1133 private static string GetTransferEncodingName (TransferEncoding encoding)
1136 case TransferEncoding.QuotedPrintable:
1137 return "quoted-printable";
1138 case TransferEncoding.SevenBit:
1140 case TransferEncoding.Base64:
1147 RemoteCertificateValidationCallback callback = delegate (object sender,
1148 X509Certificate certificate,
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);
1161 private void InitiateSecureConnection () {
1162 SmtpResponse response = SendCommand ("STARTTLS");
1164 if (IsError (response)) {
1165 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1169 SslStream sslStream = new SslStream (stream, false, callback, null);
1170 CheckCancellation ();
1171 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1175 throw new SystemException ("You are using an incomplete System.dll build");
1179 void Authenticate ()
1181 string user = null, pass = null;
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;
1193 Authenticate (user, pass);
1196 void CheckStatus (SmtpResponse status, int i)
1198 if (((int) status.StatusCode) != i)
1199 throw new SmtpException (status.StatusCode, status.Description);
1202 void ThrowIfError (SmtpResponse status)
1204 if (IsError (status))
1205 throw new SmtpException (status.StatusCode, status.Description);
1208 void Authenticate (string user, string password)
1210 if (authMechs == AuthMechs.None)
1213 SmtpResponse status;
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);
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);
1239 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1243 #endregion // Methods
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";
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;
1267 public static SmtpResponse Parse (string line) {
1268 SmtpResponse response = new SmtpResponse ();
1270 if (line.Length < 4)
1271 throw new SmtpException ("Response is to short " +
1274 if ((line [3] != ' ') && (line [3] != '-'))
1275 throw new SmtpException ("Response format is wrong.(" +
1278 // parse the response code
1279 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1281 // set the raw response
1282 response.Description = line;
1289 class CCredentialsByHost : ICredentialsByHost
1291 public CCredentialsByHost (string userName, string password) {
1292 this.userName = userName;
1293 this.password = password;
1296 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1297 return new NetworkCredential (userName, password);
1300 private string userName;
1301 private string password;