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.
34 extern alias PrebuiltSystem;
38 using System.Collections.Generic;
39 using System.ComponentModel;
40 using System.Globalization;
43 using System.Net.Mime;
44 using System.Net.Sockets;
45 using System.Security.Cryptography.X509Certificates;
47 using System.Threading;
48 using System.Reflection;
49 using System.Net.Configuration;
50 using System.Configuration;
51 using System.Net.Security;
52 using System.Security.Authentication;
55 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
58 namespace System.Net.Mail {
59 public class SmtpClient
66 ICredentialsByHost credentials;
67 string pickupDirectoryLocation;
68 SmtpDeliveryMethod deliveryMethod;
71 X509CertificateCollection clientCertificates;
79 MailAddress defaultFrom;
81 MailMessage messageInProcess;
83 BackgroundWorker worker;
84 object user_async_state;
98 class CancellationException : Exception
102 AuthMechs authMechs = AuthMechs.None;
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 if (cfg.Network.UserName != null) {
127 string password = String.Empty;
129 if (cfg.Network.Password != null)
130 password = cfg.Network.Password;
132 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
135 if (cfg.From != null)
136 defaultFrom = new MailAddress (cfg.From);
140 if (!String.IsNullOrEmpty (host))
147 #endregion // Constructors
152 [MonoTODO("Client certificates not used")]
153 public X509CertificateCollection ClientCertificates {
155 if (clientCertificates == null)
156 clientCertificates = new X509CertificateCollection ();
157 return clientCertificates;
162 public ICredentialsByHost Credentials {
163 get { return credentials; }
170 public SmtpDeliveryMethod DeliveryMethod {
171 get { return deliveryMethod; }
174 deliveryMethod = value;
178 public bool EnableSsl {
179 get { return enableSsl; }
190 throw new ArgumentNullException ("value");
191 if (value.Length == 0)
192 throw new ArgumentException ("An empty string is not allowed.", "value");
198 public string PickupDirectoryLocation {
199 get { return pickupDirectoryLocation; }
200 set { pickupDirectoryLocation = value; }
207 throw new ArgumentOutOfRangeException ("value");
214 public ServicePoint ServicePoint {
215 get { throw new NotImplementedException (); }
219 get { return timeout; }
222 throw new ArgumentOutOfRangeException ("value");
228 public bool UseDefaultCredentials {
229 get { return false; }
230 [MonoNotSupported ("no DefaultCredential support in Mono")]
233 throw new NotImplementedException ("Default credentials are not supported");
238 #endregion // Properties
242 public event SendCompletedEventHandler SendCompleted;
248 private void CheckState ()
250 if (messageInProcess != null)
251 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
254 private static string EncodeAddress(MailAddress address)
256 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
257 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
260 private static string EncodeAddresses(MailAddressCollection addresses)
262 StringBuilder sb = new StringBuilder();
264 foreach (MailAddress address in addresses) {
268 sb.Append(EncodeAddress(address));
271 return sb.ToString();
274 private string EncodeSubjectRFC2047 (MailMessage message)
276 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
279 private string EncodeBody (MailMessage message)
281 string body = message.Body;
282 Encoding encoding = message.BodyEncoding;
284 switch (message.ContentTransferEncoding) {
285 case TransferEncoding.SevenBit:
287 case TransferEncoding.Base64:
288 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
290 return ToQuotedPrintable (body, encoding);
294 private string EncodeBody (AlternateView av)
296 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
298 byte [] bytes = new byte [av.ContentStream.Length];
299 av.ContentStream.Read (bytes, 0, bytes.Length);
302 switch (av.TransferEncoding) {
303 case TransferEncoding.SevenBit:
304 return Encoding.ASCII.GetString (bytes);
305 case TransferEncoding.Base64:
306 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
308 return ToQuotedPrintable (bytes);
313 private void EndSection (string section)
315 SendData (String.Format ("--{0}--", section));
316 SendData (string.Empty);
319 private string GenerateBoundary ()
321 string output = GenerateBoundary (boundaryIndex);
326 private static string GenerateBoundary (int index)
328 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
331 private bool IsError (SmtpResponse status)
333 return ((int) status.StatusCode) >= 400;
336 protected void OnSendCompleted (AsyncCompletedEventArgs e)
339 if (SendCompleted != null)
340 SendCompleted (this, e);
343 user_async_state = null;
347 private void CheckCancellation ()
349 if (worker != null && worker.CancellationPending)
350 throw new CancellationException ();
353 private SmtpResponse Read () {
354 byte [] buffer = new byte [512];
356 bool lastLine = false;
359 CheckCancellation ();
361 int readLength = stream.Read (buffer, position, buffer.Length - position);
362 if (readLength > 0) {
363 int available = position + readLength - 1;
364 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
365 for (int index = available - 3; ; index--) {
366 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
367 lastLine = buffer [index + 4] == ' ';
373 position += readLength;
375 // check if buffer is full
376 if (position == buffer.Length) {
377 byte [] newBuffer = new byte [buffer.Length * 2];
378 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
388 Encoding encoding = new ASCIIEncoding ();
390 string line = encoding.GetString (buffer, 0, position - 1);
392 // parse the line to the lastResponse object
393 SmtpResponse response = SmtpResponse.Parse (line);
397 throw new System.IO.IOException ("Connection closed");
401 void ResetExtensions()
403 authMechs = AuthMechs.None;
406 void ParseExtensions (string extens)
408 char[] delims = new char [1] { ' ' };
409 string[] parts = extens.Split ('\n');
411 foreach (string part in parts) {
415 string start = part.Substring (4);
416 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
417 string[] options = start.Split (delims);
418 for (int k = 1; k < options.Length; k++) {
419 string option = options[k].Trim();
422 authMechs |= AuthMechs.CramMD5;
425 authMechs |= AuthMechs.DigestMD5;
428 authMechs |= AuthMechs.GssAPI;
431 authMechs |= AuthMechs.Kerberos4;
434 authMechs |= AuthMechs.Login;
437 authMechs |= AuthMechs.Plain;
445 public void Send (MailMessage message)
448 throw new ArgumentNullException ("message");
450 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
451 throw new InvalidOperationException ("The SMTP host was not specified");
452 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
453 throw new NotSupportedException("IIS delivery is not supported");
458 // Block while sending
461 messageInProcess = message;
462 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
463 SendToFile (message);
465 SendInternal (message);
466 } catch (CancellationException) {
467 // This exception is introduced for convenient cancellation process.
468 } catch (SmtpException) {
470 } catch (Exception ex) {
471 throw new SmtpException ("Message could not be sent.", ex);
473 // Release the mutex to allow other threads access
474 mutex.ReleaseMutex ();
475 messageInProcess = null;
479 private void SendInternal (MailMessage message)
481 CheckCancellation ();
484 client = new TcpClient (host, port);
485 stream = client.GetStream ();
486 // FIXME: this StreamWriter creation is bogus.
487 // It expects as if a Stream were able to switch to SSL
488 // mode (such behavior is only in Mainsoft Socket API).
489 writer = new StreamWriter (stream);
490 reader = new StreamReader (stream);
505 // FIXME: simple implementation, could be brushed up.
506 private void SendToFile (MailMessage message)
508 if (!Path.IsPathRooted (pickupDirectoryLocation))
509 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
511 string filename = Path.Combine (pickupDirectoryLocation,
512 Guid.NewGuid() + ".eml");
515 writer = new StreamWriter(filename);
517 MailAddress from = message.From;
522 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
523 SendHeader (HeaderName.From, from.ToString ());
524 SendHeader (HeaderName.To, message.To.ToString ());
525 if (message.CC.Count > 0)
526 SendHeader (HeaderName.Cc, message.CC.ToString ());
527 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
529 foreach (string s in message.Headers.AllKeys)
530 SendHeader (s, message.Headers [s]);
532 AddPriorityHeader (message);
535 if (message.Attachments.Count > 0)
536 SendWithAttachments (message);
538 SendWithoutAttachments (message, null, false);
542 if (writer != null) writer.Close(); writer = null;
546 private void SendCore (MailMessage message)
551 if (IsError (status))
552 throw new SmtpException (status.StatusCode, status.Description);
556 // FIXME: parse the list of extensions so we don't bother wasting
557 // our time trying commands if they aren't supported.
558 status = SendCommand ("EHLO " + Dns.GetHostName ());
560 if (IsError (status)) {
561 status = SendCommand ("HELO " + Dns.GetHostName ());
563 if (IsError (status))
564 throw new SmtpException (status.StatusCode, status.Description);
566 // Parse ESMTP extensions
567 string extens = status.Description;
570 ParseExtensions (extens);
574 InitiateSecureConnection ();
576 writer = new StreamWriter (stream);
577 reader = new StreamReader (stream);
578 status = SendCommand ("EHLO " + Dns.GetHostName ());
580 if (IsError (status)) {
581 status = SendCommand ("HELO " + Dns.GetHostName ());
583 if (IsError (status))
584 throw new SmtpException (status.StatusCode, status.Description);
586 // Parse ESMTP extensions
587 string extens = status.Description;
589 ParseExtensions (extens);
593 if (authMechs != AuthMechs.None)
596 MailAddress from = message.From;
602 status = SendCommand ("MAIL FROM:<" + from.Address + '>');
603 if (IsError (status)) {
604 throw new SmtpException (status.StatusCode, status.Description);
607 // Send RCPT TO: for all recipients
608 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
610 for (int i = 0; i < message.To.Count; i ++) {
611 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
612 if (IsError (status))
613 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
615 for (int i = 0; i < message.CC.Count; i ++) {
616 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
617 if (IsError (status))
618 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
620 for (int i = 0; i < message.Bcc.Count; i ++) {
621 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
622 if (IsError (status))
623 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
626 #if TARGET_JVM // List<T>.ToArray () is not supported
627 if (sfre.Count > 0) {
628 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
630 throw new SmtpFailedRecipientsException ("failed recipients", xs);
634 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
638 status = SendCommand ("DATA");
639 if (IsError (status))
640 throw new SmtpException (status.StatusCode, status.Description);
642 // Send message headers
643 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
644 // remove ':' from time zone offset (e.g. from "+01:00")
645 dt = dt.Remove (dt.Length - 3, 1);
646 SendHeader (HeaderName.Date, dt);
648 SendHeader (HeaderName.From, EncodeAddress (from));
649 SendHeader (HeaderName.To, EncodeAddresses (message.To));
650 if (message.CC.Count > 0)
651 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
652 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
656 switch (message.Priority){
657 case MailPriority.Normal:
661 case MailPriority.Low:
665 case MailPriority.High:
669 SendHeader ("Priority", v);
670 if (message.Sender != null)
671 SendHeader ("Sender", EncodeAddress (message.Sender));
672 if (message.ReplyTo != null)
673 SendHeader ("ReplyTo", EncodeAddress (message.ReplyTo));
675 foreach (string s in message.Headers.AllKeys)
676 SendHeader (s, message.Headers [s]);
678 AddPriorityHeader (message);
681 if (message.Attachments.Count > 0)
682 SendWithAttachments (message);
684 SendWithoutAttachments (message, null, false);
689 if (IsError (status))
690 throw new SmtpException (status.StatusCode, status.Description);
693 status = SendCommand ("QUIT");
694 } catch (System.IO.IOException) {
695 // We excuse server for the rude connection closing as a response to QUIT
699 public void Send (string from, string to, string subject, string body)
701 Send (new MailMessage (from, to, subject, body));
704 private void SendData (string data)
706 CheckCancellation ();
708 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
709 StringBuilder sb = new StringBuilder (data);
710 sb.Replace ("\r\n", "\n");
711 sb.Replace ('\r', '\n');
712 sb.Replace ("\n", "\r\n");
713 writer.Write (sb.ToString ());
714 writer.Write ("\r\n");
718 public void SendAsync (MailMessage message, object userToken)
721 throw new InvalidOperationException ("Another SendAsync operation is in progress");
723 worker = new BackgroundWorker ();
724 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
726 user_async_state = ea.Argument;
728 } catch (Exception ex) {
732 worker.WorkerSupportsCancellation = true;
733 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
734 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
735 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
737 worker.RunWorkerAsync (userToken);
740 public void SendAsync (string from, string to, string subject, string body, object userToken)
742 SendAsync (new MailMessage (from, to, subject, body), userToken);
745 public void SendAsyncCancel ()
748 throw new InvalidOperationException ("SendAsync operation is not in progress");
749 worker.CancelAsync ();
752 private void AddPriorityHeader (MailMessage message) {
753 switch (message.Priority) {
754 case MailPriority.High:
755 SendHeader (HeaderName.Priority, "Urgent");
756 SendHeader (HeaderName.Importance, "high");
757 SendHeader (HeaderName.XPriority, "1");
759 case MailPriority.Low:
760 SendHeader (HeaderName.Priority, "Non-Urgent");
761 SendHeader (HeaderName.Importance, "low");
762 SendHeader (HeaderName.XPriority, "5");
767 private void SendSimpleBody (MailMessage message) {
768 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
769 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
770 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
771 SendData (string.Empty);
773 SendData (EncodeBody (message));
776 private void SendBodylessSingleAlternate (AlternateView av) {
777 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
778 if (av.TransferEncoding != TransferEncoding.SevenBit)
779 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
780 SendData (string.Empty);
782 SendData (EncodeBody (av));
785 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
787 if (message.Body == null && message.AlternateViews.Count == 1)
788 SendBodylessSingleAlternate (message.AlternateViews [0]);
789 else if (message.AlternateViews.Count > 0)
790 SendBodyWithAlternateViews (message, boundary, attachmentExists);
792 SendSimpleBody (message);
796 private void SendWithAttachments (MailMessage message) {
797 string boundary = GenerateBoundary ();
799 // first "multipart/mixed"
800 ContentType messageContentType = new ContentType ();
801 messageContentType.Boundary = boundary;
802 messageContentType.MediaType = "multipart/mixed";
803 messageContentType.CharSet = null;
805 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
806 SendData (String.Empty);
809 Attachment body = null;
811 if (message.AlternateViews.Count > 0)
812 SendWithoutAttachments (message, boundary, true);
814 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
815 message.Attachments.Insert (0, body);
819 SendAttachments (message, body, boundary);
822 message.Attachments.Remove (body);
825 EndSection (boundary);
828 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
830 AlternateViewCollection alternateViews = message.AlternateViews;
832 string inner_boundary = GenerateBoundary ();
834 ContentType messageContentType = new ContentType ();
835 messageContentType.Boundary = inner_boundary;
836 messageContentType.MediaType = "multipart/alternative";
838 if (!attachmentExists) {
839 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
840 SendData (String.Empty);
844 AlternateView body = null;
845 if (message.Body != null) {
846 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
847 alternateViews.Insert (0, body);
848 StartSection (boundary, messageContentType);
852 // alternate view sections
853 foreach (AlternateView av in alternateViews) {
855 string alt_boundary = null;
856 ContentType contentType;
857 if (av.LinkedResources.Count > 0) {
858 alt_boundary = GenerateBoundary ();
859 contentType = new ContentType ("multipart/related");
860 contentType.Boundary = alt_boundary;
861 contentType.Parameters ["type"] = "application/octet-stream";
862 StartSection (inner_boundary, contentType);
864 contentType = new ContentType (av.ContentType.ToString ());
865 StartSection (inner_boundary, contentType, av.TransferEncoding);
868 switch (av.TransferEncoding) {
869 case TransferEncoding.Base64:
870 byte [] content = new byte [av.ContentStream.Length];
871 av.ContentStream.Read (content, 0, content.Length);
873 SendData (Convert.ToBase64String (content));
875 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
878 case TransferEncoding.QuotedPrintable:
879 byte [] bytes = new byte [av.ContentStream.Length];
880 av.ContentStream.Read (bytes, 0, bytes.Length);
881 SendData (ToQuotedPrintable (bytes));
883 case TransferEncoding.SevenBit:
884 case TransferEncoding.Unknown:
885 content = new byte [av.ContentStream.Length];
886 av.ContentStream.Read (content, 0, content.Length);
887 SendData (Encoding.ASCII.GetString (content));
891 if (av.LinkedResources.Count > 0) {
892 SendLinkedResources (message, av.LinkedResources, alt_boundary);
893 EndSection (alt_boundary);
896 if (!attachmentExists)
897 SendData (string.Empty);
902 alternateViews.Remove (body);
904 EndSection (inner_boundary);
907 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
909 foreach (LinkedResource lr in resources) {
910 ContentType contentType = new ContentType (lr.ContentType.ToString ());
911 StartSection (boundary, contentType, lr.TransferEncoding);
913 switch (lr.TransferEncoding) {
914 case TransferEncoding.Base64:
915 byte [] content = new byte [lr.ContentStream.Length];
916 lr.ContentStream.Read (content, 0, content.Length);
918 SendData (Convert.ToBase64String (content));
920 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
923 case TransferEncoding.QuotedPrintable:
924 byte [] bytes = new byte [lr.ContentStream.Length];
925 lr.ContentStream.Read (bytes, 0, bytes.Length);
926 SendData (ToQuotedPrintable (bytes));
928 case TransferEncoding.SevenBit:
929 case TransferEncoding.Unknown:
930 content = new byte [lr.ContentStream.Length];
931 lr.ContentStream.Read (content, 0, content.Length);
932 SendData (Encoding.ASCII.GetString (content));
938 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
939 foreach (Attachment att in message.Attachments) {
940 ContentType contentType = new ContentType (att.ContentType.ToString ());
941 if (att.Name != null) {
942 contentType.Name = att.Name;
943 if (att.NameEncoding != null)
944 contentType.CharSet = att.NameEncoding.HeaderName;
945 att.ContentDisposition.FileName = att.Name;
947 StartSection (boundary, contentType, att.TransferEncoding, att == body ? null : att.ContentDisposition);
949 byte [] content = new byte [att.ContentStream.Length];
950 att.ContentStream.Read (content, 0, content.Length);
951 switch (att.TransferEncoding) {
952 case TransferEncoding.Base64:
954 SendData (Convert.ToBase64String (content));
956 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
959 case TransferEncoding.QuotedPrintable:
960 SendData (ToQuotedPrintable (content));
962 case TransferEncoding.SevenBit:
963 case TransferEncoding.Unknown:
964 SendData (Encoding.ASCII.GetString (content));
968 SendData (string.Empty);
972 private SmtpResponse SendCommand (string command)
974 writer.Write (command);
975 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
976 writer.Write ("\r\n");
981 private void SendHeader (string name, string value)
983 SendData (String.Format ("{0}: {1}", name, value));
986 private void StartSection (string section, ContentType sectionContentType)
988 SendData (String.Format ("--{0}", section));
989 SendHeader ("content-type", sectionContentType.ToString ());
990 SendData (string.Empty);
993 private void StartSection (string section, ContentType sectionContentType,TransferEncoding transferEncoding)
995 SendData (String.Format ("--{0}", section));
996 SendHeader ("content-type", sectionContentType.ToString ());
997 SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
998 SendData (string.Empty);
1001 private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) {
1002 SendData (String.Format ("--{0}", section));
1003 SendHeader ("content-type", sectionContentType.ToString ());
1004 SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
1005 if (contentDisposition != null)
1006 SendHeader ("content-disposition", contentDisposition.ToString ());
1007 SendData (string.Empty);
1010 // use proper encoding to escape input
1011 private string ToQuotedPrintable (string input, Encoding enc)
1013 byte [] bytes = enc.GetBytes (input);
1014 return ToQuotedPrintable (bytes);
1017 private string ToQuotedPrintable (byte [] bytes)
1019 StringWriter writer = new StringWriter ();
1020 int charsInLine = 0;
1022 StringBuilder sb = new StringBuilder("=", 3);
1023 byte equalSign = (byte)'=';
1026 foreach (byte i in bytes) {
1027 if (i > 127 || i == equalSign) {
1029 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1032 c = Convert.ToChar (i);
1033 if (c == '\r' || c == '\n') {
1041 charsInLine += curLen;
1042 if (charsInLine > 75) {
1043 writer.Write ("=\r\n");
1044 charsInLine = curLen;
1049 writer.Write (sb.ToString ());
1052 return writer.ToString ();
1054 private static string GetTransferEncodingName (TransferEncoding encoding)
1057 case TransferEncoding.QuotedPrintable:
1058 return "quoted-printable";
1059 case TransferEncoding.SevenBit:
1061 case TransferEncoding.Base64:
1068 RemoteCertificateValidationCallback callback = delegate (object sender,
1069 X509Certificate certificate,
1071 SslPolicyErrors sslPolicyErrors) {
1072 if (sslPolicyErrors != SslPolicyErrors.None)
1073 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1078 private void InitiateSecureConnection () {
1079 SmtpResponse response = SendCommand ("STARTTLS");
1081 if (IsError (response)) {
1082 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1086 ((NetworkStream) stream).ChangeToSSLSocket ();
1088 SslStream sslStream = new SslStream (stream, false, callback, null);
1089 CheckCancellation ();
1090 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1094 throw new SystemException ("You are using an incomplete System.dll build");
1098 void Authenticate ()
1100 string user = null, pass = null;
1102 if (UseDefaultCredentials) {
1103 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1104 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1105 } else if (Credentials != null) {
1106 user = Credentials.GetCredential (host, port, "smtp").UserName;
1107 pass = Credentials.GetCredential (host, port, "smtp").Password;
1112 Authenticate (user, pass);
1115 void Authenticate (string Username, string Password)
1117 // FIXME: use the proper AuthMech
1118 SmtpResponse status = SendCommand ("AUTH LOGIN");
1119 if (((int) status.StatusCode) != 334) {
1120 throw new SmtpException (status.StatusCode, status.Description);
1123 status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Username)));
1124 if (((int) status.StatusCode) != 334) {
1125 throw new SmtpException (status.StatusCode, status.Description);
1128 status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Password)));
1129 if (IsError (status)) {
1130 throw new SmtpException (status.StatusCode, status.Description);
1134 #endregion // Methods
1136 // The HeaderName struct is used to store constant string values representing mail headers.
1137 private struct HeaderName {
1138 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1139 public const string ContentType = "Content-Type";
1140 public const string Bcc = "Bcc";
1141 public const string Cc = "Cc";
1142 public const string From = "From";
1143 public const string Subject = "Subject";
1144 public const string To = "To";
1145 public const string MimeVersion = "MIME-Version";
1146 public const string MessageId = "Message-ID";
1147 public const string Priority = "Priority";
1148 public const string Importance = "Importance";
1149 public const string XPriority = "X-Priority";
1150 public const string Date = "Date";
1153 // This object encapsulates the status code and description of an SMTP response.
1154 private struct SmtpResponse {
1155 public SmtpStatusCode StatusCode;
1156 public string Description;
1158 public static SmtpResponse Parse (string line) {
1159 SmtpResponse response = new SmtpResponse ();
1161 if (line.Length < 4)
1162 throw new SmtpException ("Response is to short " +
1165 if ((line [3] != ' ') && (line [3] != '-'))
1166 throw new SmtpException ("Response format is wrong.(" +
1169 // parse the response code
1170 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1172 // set the raw response
1173 response.Description = line;
1180 class CCredentialsByHost : ICredentialsByHost
1182 public CCredentialsByHost (string userName, string password) {
1183 this.userName = userName;
1184 this.password = password;
1187 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1188 return new NetworkCredential (userName, password);
1191 private string userName;
1192 private string password;