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 TargetName = cfg.Network.TargetName;
127 if (this.TargetName == null)
128 TargetName = "SMTPSVC/" + (host != null ? host : "");
131 if (cfg.Network.UserName != null) {
132 string password = String.Empty;
134 if (cfg.Network.Password != null)
135 password = cfg.Network.Password;
137 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
140 if (cfg.From != null)
141 defaultFrom = new MailAddress (cfg.From);
145 if (!String.IsNullOrEmpty (host))
152 #endregion // Constructors
157 [MonoTODO("Client certificates not used")]
158 public X509CertificateCollection ClientCertificates {
160 if (clientCertificates == null)
161 clientCertificates = new X509CertificateCollection ();
162 return clientCertificates;
170 string TargetName { get; set; }
172 public ICredentialsByHost Credentials {
173 get { return credentials; }
180 public SmtpDeliveryMethod DeliveryMethod {
181 get { return deliveryMethod; }
184 deliveryMethod = value;
188 public bool EnableSsl {
189 get { return enableSsl; }
200 throw new ArgumentNullException ("value");
201 if (value.Length == 0)
202 throw new ArgumentException ("An empty string is not allowed.", "value");
208 public string PickupDirectoryLocation {
209 get { return pickupDirectoryLocation; }
210 set { pickupDirectoryLocation = value; }
217 throw new ArgumentOutOfRangeException ("value");
224 public ServicePoint ServicePoint {
225 get { throw new NotImplementedException (); }
229 get { return timeout; }
232 throw new ArgumentOutOfRangeException ("value");
238 public bool UseDefaultCredentials {
239 get { return false; }
240 [MonoNotSupported ("no DefaultCredential support in Mono")]
243 throw new NotImplementedException ("Default credentials are not supported");
248 #endregion // Properties
252 public event SendCompletedEventHandler SendCompleted;
258 private void CheckState ()
260 if (messageInProcess != null)
261 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
264 private static string EncodeAddress(MailAddress address)
266 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
267 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
270 private static string EncodeAddresses(MailAddressCollection addresses)
272 StringBuilder sb = new StringBuilder();
274 foreach (MailAddress address in addresses) {
278 sb.Append(EncodeAddress(address));
281 return sb.ToString();
284 private string EncodeSubjectRFC2047 (MailMessage message)
286 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
289 private string EncodeBody (MailMessage message)
291 string body = message.Body;
292 Encoding encoding = message.BodyEncoding;
294 switch (message.ContentTransferEncoding) {
295 case TransferEncoding.SevenBit:
297 case TransferEncoding.Base64:
298 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
300 return ToQuotedPrintable (body, encoding);
304 private string EncodeBody (AlternateView av)
306 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
308 byte [] bytes = new byte [av.ContentStream.Length];
309 av.ContentStream.Read (bytes, 0, bytes.Length);
312 switch (av.TransferEncoding) {
313 case TransferEncoding.SevenBit:
314 return Encoding.ASCII.GetString (bytes);
315 case TransferEncoding.Base64:
316 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
318 return ToQuotedPrintable (bytes);
323 private void EndSection (string section)
325 SendData (String.Format ("--{0}--", section));
326 SendData (string.Empty);
329 private string GenerateBoundary ()
331 string output = GenerateBoundary (boundaryIndex);
336 private static string GenerateBoundary (int index)
338 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
341 private bool IsError (SmtpResponse status)
343 return ((int) status.StatusCode) >= 400;
346 protected void OnSendCompleted (AsyncCompletedEventArgs e)
349 if (SendCompleted != null)
350 SendCompleted (this, e);
353 user_async_state = null;
357 private void CheckCancellation ()
359 if (worker != null && worker.CancellationPending)
360 throw new CancellationException ();
363 private SmtpResponse Read () {
364 byte [] buffer = new byte [512];
366 bool lastLine = false;
369 CheckCancellation ();
371 int readLength = stream.Read (buffer, position, buffer.Length - position);
372 if (readLength > 0) {
373 int available = position + readLength - 1;
374 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
375 for (int index = available - 3; ; index--) {
376 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
377 lastLine = buffer [index + 4] == ' ';
383 position += readLength;
385 // check if buffer is full
386 if (position == buffer.Length) {
387 byte [] newBuffer = new byte [buffer.Length * 2];
388 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
398 Encoding encoding = new ASCIIEncoding ();
400 string line = encoding.GetString (buffer, 0, position - 1);
402 // parse the line to the lastResponse object
403 SmtpResponse response = SmtpResponse.Parse (line);
407 throw new System.IO.IOException ("Connection closed");
411 void ResetExtensions()
413 authMechs = AuthMechs.None;
416 void ParseExtensions (string extens)
418 char[] delims = new char [1] { ' ' };
419 string[] parts = extens.Split ('\n');
421 foreach (string part in parts) {
425 string start = part.Substring (4);
426 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
427 string[] options = start.Split (delims);
428 for (int k = 1; k < options.Length; k++) {
429 string option = options[k].Trim();
432 authMechs |= AuthMechs.CramMD5;
435 authMechs |= AuthMechs.DigestMD5;
438 authMechs |= AuthMechs.GssAPI;
441 authMechs |= AuthMechs.Kerberos4;
444 authMechs |= AuthMechs.Login;
447 authMechs |= AuthMechs.Plain;
455 public void Send (MailMessage message)
458 throw new ArgumentNullException ("message");
460 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
461 throw new InvalidOperationException ("The SMTP host was not specified");
462 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
463 throw new NotSupportedException("IIS delivery is not supported");
468 // Block while sending
471 messageInProcess = message;
472 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
473 SendToFile (message);
475 SendInternal (message);
476 } catch (CancellationException) {
477 // This exception is introduced for convenient cancellation process.
478 } catch (SmtpException) {
480 } catch (Exception ex) {
481 throw new SmtpException ("Message could not be sent.", ex);
483 // Release the mutex to allow other threads access
484 mutex.ReleaseMutex ();
485 messageInProcess = null;
489 private void SendInternal (MailMessage message)
491 CheckCancellation ();
494 client = new TcpClient (host, port);
495 stream = client.GetStream ();
496 // FIXME: this StreamWriter creation is bogus.
497 // It expects as if a Stream were able to switch to SSL
498 // mode (such behavior is only in Mainsoft Socket API).
499 writer = new StreamWriter (stream);
500 reader = new StreamReader (stream);
515 // FIXME: simple implementation, could be brushed up.
516 private void SendToFile (MailMessage message)
518 if (!Path.IsPathRooted (pickupDirectoryLocation))
519 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
521 string filename = Path.Combine (pickupDirectoryLocation,
522 Guid.NewGuid() + ".eml");
525 writer = new StreamWriter(filename);
527 MailAddress from = message.From;
532 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
533 SendHeader (HeaderName.From, from.ToString ());
534 SendHeader (HeaderName.To, message.To.ToString ());
535 if (message.CC.Count > 0)
536 SendHeader (HeaderName.Cc, message.CC.ToString ());
537 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
539 foreach (string s in message.Headers.AllKeys)
540 SendHeader (s, message.Headers [s]);
542 AddPriorityHeader (message);
545 if (message.Attachments.Count > 0)
546 SendWithAttachments (message);
548 SendWithoutAttachments (message, null, false);
552 if (writer != null) writer.Close(); writer = null;
556 private void SendCore (MailMessage message)
561 if (IsError (status))
562 throw new SmtpException (status.StatusCode, status.Description);
566 // FIXME: parse the list of extensions so we don't bother wasting
567 // our time trying commands if they aren't supported.
568 status = SendCommand ("EHLO " + Dns.GetHostName ());
570 if (IsError (status)) {
571 status = SendCommand ("HELO " + Dns.GetHostName ());
573 if (IsError (status))
574 throw new SmtpException (status.StatusCode, status.Description);
576 // Parse ESMTP extensions
577 string extens = status.Description;
580 ParseExtensions (extens);
584 InitiateSecureConnection ();
586 writer = new StreamWriter (stream);
587 reader = new StreamReader (stream);
588 status = SendCommand ("EHLO " + Dns.GetHostName ());
590 if (IsError (status)) {
591 status = SendCommand ("HELO " + Dns.GetHostName ());
593 if (IsError (status))
594 throw new SmtpException (status.StatusCode, status.Description);
596 // Parse ESMTP extensions
597 string extens = status.Description;
599 ParseExtensions (extens);
603 if (authMechs != AuthMechs.None)
606 MailAddress from = message.From;
612 status = SendCommand ("MAIL FROM:<" + from.Address + '>');
613 if (IsError (status)) {
614 throw new SmtpException (status.StatusCode, status.Description);
617 // Send RCPT TO: for all recipients
618 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
620 for (int i = 0; i < message.To.Count; i ++) {
621 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
622 if (IsError (status))
623 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
625 for (int i = 0; i < message.CC.Count; i ++) {
626 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
627 if (IsError (status))
628 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
630 for (int i = 0; i < message.Bcc.Count; i ++) {
631 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
632 if (IsError (status))
633 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
636 #if TARGET_JVM // List<T>.ToArray () is not supported
637 if (sfre.Count > 0) {
638 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
640 throw new SmtpFailedRecipientsException ("failed recipients", xs);
644 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
648 status = SendCommand ("DATA");
649 if (IsError (status))
650 throw new SmtpException (status.StatusCode, status.Description);
652 // Send message headers
653 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
654 // remove ':' from time zone offset (e.g. from "+01:00")
655 dt = dt.Remove (dt.Length - 3, 1);
656 SendHeader (HeaderName.Date, dt);
658 SendHeader (HeaderName.From, EncodeAddress (from));
659 SendHeader (HeaderName.To, EncodeAddresses (message.To));
660 if (message.CC.Count > 0)
661 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
662 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
666 switch (message.Priority){
667 case MailPriority.Normal:
671 case MailPriority.Low:
675 case MailPriority.High:
679 SendHeader ("Priority", v);
680 if (message.Sender != null)
681 SendHeader ("Sender", EncodeAddress (message.Sender));
682 if (message.ReplyToList.Count > 0)
683 SendHeader ("ReplyTo", EncodeAddresses (message.ReplyToList));
686 foreach (string s in message.Headers.AllKeys)
687 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
689 foreach (string s in message.Headers.AllKeys)
690 SendHeader (s, message.Headers [s]);
693 AddPriorityHeader (message);
696 if (message.Attachments.Count > 0)
697 SendWithAttachments (message);
699 SendWithoutAttachments (message, null, false);
704 if (IsError (status))
705 throw new SmtpException (status.StatusCode, status.Description);
708 status = SendCommand ("QUIT");
709 } catch (System.IO.IOException) {
710 // We excuse server for the rude connection closing as a response to QUIT
714 public void Send (string from, string to, string subject, string body)
716 Send (new MailMessage (from, to, subject, body));
719 private void SendDot()
721 writer.Write(".\r\n");
725 private void SendData (string data)
727 if (String.IsNullOrEmpty (data)) {
728 writer.Write("\r\n");
733 StringReader sr = new StringReader (data);
735 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
736 while ((line = sr.ReadLine ()) != null) {
737 CheckCancellation ();
741 for (i = 0; i < line.Length; i++) {
745 if (i > 0 && i == line.Length) {
750 writer.Write ("\r\n");
755 public void SendAsync (MailMessage message, object userToken)
758 throw new InvalidOperationException ("Another SendAsync operation is in progress");
760 worker = new BackgroundWorker ();
761 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
763 user_async_state = ea.Argument;
765 } catch (Exception ex) {
770 worker.WorkerSupportsCancellation = true;
771 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
772 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
773 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
775 worker.RunWorkerAsync (userToken);
778 public void SendAsync (string from, string to, string subject, string body, object userToken)
780 SendAsync (new MailMessage (from, to, subject, body), userToken);
783 public void SendAsyncCancel ()
786 throw new InvalidOperationException ("SendAsync operation is not in progress");
787 worker.CancelAsync ();
790 private void AddPriorityHeader (MailMessage message) {
791 switch (message.Priority) {
792 case MailPriority.High:
793 SendHeader (HeaderName.Priority, "Urgent");
794 SendHeader (HeaderName.Importance, "high");
795 SendHeader (HeaderName.XPriority, "1");
797 case MailPriority.Low:
798 SendHeader (HeaderName.Priority, "Non-Urgent");
799 SendHeader (HeaderName.Importance, "low");
800 SendHeader (HeaderName.XPriority, "5");
805 private void SendSimpleBody (MailMessage message) {
806 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
807 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
808 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
809 SendData (string.Empty);
811 SendData (EncodeBody (message));
814 private void SendBodylessSingleAlternate (AlternateView av) {
815 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
816 if (av.TransferEncoding != TransferEncoding.SevenBit)
817 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
818 SendData (string.Empty);
820 SendData (EncodeBody (av));
823 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
825 if (message.Body == null && message.AlternateViews.Count == 1)
826 SendBodylessSingleAlternate (message.AlternateViews [0]);
827 else if (message.AlternateViews.Count > 0)
828 SendBodyWithAlternateViews (message, boundary, attachmentExists);
830 SendSimpleBody (message);
834 private void SendWithAttachments (MailMessage message) {
835 string boundary = GenerateBoundary ();
837 // first "multipart/mixed"
838 ContentType messageContentType = new ContentType ();
839 messageContentType.Boundary = boundary;
840 messageContentType.MediaType = "multipart/mixed";
841 messageContentType.CharSet = null;
843 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
844 SendData (String.Empty);
847 Attachment body = null;
849 if (message.AlternateViews.Count > 0)
850 SendWithoutAttachments (message, boundary, true);
852 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
853 message.Attachments.Insert (0, body);
857 SendAttachments (message, body, boundary);
860 message.Attachments.Remove (body);
863 EndSection (boundary);
866 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
868 AlternateViewCollection alternateViews = message.AlternateViews;
870 string inner_boundary = GenerateBoundary ();
872 ContentType messageContentType = new ContentType ();
873 messageContentType.Boundary = inner_boundary;
874 messageContentType.MediaType = "multipart/alternative";
876 if (!attachmentExists) {
877 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
878 SendData (String.Empty);
882 AlternateView body = null;
883 if (message.Body != null) {
884 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
885 alternateViews.Insert (0, body);
886 StartSection (boundary, messageContentType);
890 // alternate view sections
891 foreach (AlternateView av in alternateViews) {
893 string alt_boundary = null;
894 ContentType contentType;
895 if (av.LinkedResources.Count > 0) {
896 alt_boundary = GenerateBoundary ();
897 contentType = new ContentType ("multipart/related");
898 contentType.Boundary = alt_boundary;
900 contentType.Parameters ["type"] = av.ContentType.ToString ();
901 StartSection (inner_boundary, contentType);
902 StartSection (alt_boundary, av.ContentType, av.TransferEncoding);
904 contentType = new ContentType (av.ContentType.ToString ());
905 StartSection (inner_boundary, contentType, av.TransferEncoding);
908 switch (av.TransferEncoding) {
909 case TransferEncoding.Base64:
910 byte [] content = new byte [av.ContentStream.Length];
911 av.ContentStream.Read (content, 0, content.Length);
913 SendData (Convert.ToBase64String (content));
915 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
918 case TransferEncoding.QuotedPrintable:
919 byte [] bytes = new byte [av.ContentStream.Length];
920 av.ContentStream.Read (bytes, 0, bytes.Length);
921 SendData (ToQuotedPrintable (bytes));
923 case TransferEncoding.SevenBit:
924 case TransferEncoding.Unknown:
925 content = new byte [av.ContentStream.Length];
926 av.ContentStream.Read (content, 0, content.Length);
927 SendData (Encoding.ASCII.GetString (content));
931 if (av.LinkedResources.Count > 0) {
932 SendLinkedResources (message, av.LinkedResources, alt_boundary);
933 EndSection (alt_boundary);
936 if (!attachmentExists)
937 SendData (string.Empty);
942 alternateViews.Remove (body);
944 EndSection (inner_boundary);
947 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
949 foreach (LinkedResource lr in resources) {
950 StartSection (boundary, lr.ContentType, lr.TransferEncoding, lr);
952 switch (lr.TransferEncoding) {
953 case TransferEncoding.Base64:
954 byte [] content = new byte [lr.ContentStream.Length];
955 lr.ContentStream.Read (content, 0, content.Length);
957 SendData (Convert.ToBase64String (content));
959 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
962 case TransferEncoding.QuotedPrintable:
963 byte [] bytes = new byte [lr.ContentStream.Length];
964 lr.ContentStream.Read (bytes, 0, bytes.Length);
965 SendData (ToQuotedPrintable (bytes));
967 case TransferEncoding.SevenBit:
968 case TransferEncoding.Unknown:
969 content = new byte [lr.ContentStream.Length];
970 lr.ContentStream.Read (content, 0, content.Length);
971 SendData (Encoding.ASCII.GetString (content));
977 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
978 foreach (Attachment att in message.Attachments) {
979 ContentType contentType = new ContentType (att.ContentType.ToString ());
980 if (att.Name != null) {
981 contentType.Name = att.Name;
982 if (att.NameEncoding != null)
983 contentType.CharSet = att.NameEncoding.HeaderName;
984 att.ContentDisposition.FileName = att.Name;
986 StartSection (boundary, contentType, att.TransferEncoding, att == body ? null : att.ContentDisposition);
988 byte [] content = new byte [att.ContentStream.Length];
989 att.ContentStream.Read (content, 0, content.Length);
990 switch (att.TransferEncoding) {
991 case TransferEncoding.Base64:
993 SendData (Convert.ToBase64String (content));
995 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
998 case TransferEncoding.QuotedPrintable:
999 SendData (ToQuotedPrintable (content));
1001 case TransferEncoding.SevenBit:
1002 case TransferEncoding.Unknown:
1003 SendData (Encoding.ASCII.GetString (content));
1007 SendData (string.Empty);
1011 private SmtpResponse SendCommand (string command)
1013 writer.Write (command);
1014 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1015 writer.Write ("\r\n");
1020 private void SendHeader (string name, string value)
1022 SendData (String.Format ("{0}: {1}", name, value));
1025 private void StartSection (string section, ContentType sectionContentType)
1027 SendData (String.Format ("--{0}", section));
1028 SendHeader ("content-type", sectionContentType.ToString ());
1029 SendData (string.Empty);
1032 private void StartSection (string section, ContentType sectionContentType,TransferEncoding transferEncoding)
1034 SendData (String.Format ("--{0}", section));
1035 SendHeader ("content-type", sectionContentType.ToString ());
1036 SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
1037 SendData (string.Empty);
1040 private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding, LinkedResource lr)
1042 SendData (String.Format("--{0}", section));
1043 SendHeader ("content-type", sectionContentType.ToString ());
1044 SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
1046 if (lr.ContentId != null && lr.ContentId.Length > 0)
1047 SendHeader("content-ID", "<" + lr.ContentId + ">");
1049 SendData (string.Empty);
1052 private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) {
1053 SendData (String.Format ("--{0}", section));
1054 SendHeader ("content-type", sectionContentType.ToString ());
1055 SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
1056 if (contentDisposition != null)
1057 SendHeader ("content-disposition", contentDisposition.ToString ());
1058 SendData (string.Empty);
1061 // use proper encoding to escape input
1062 private string ToQuotedPrintable (string input, Encoding enc)
1064 byte [] bytes = enc.GetBytes (input);
1065 return ToQuotedPrintable (bytes);
1068 private string ToQuotedPrintable (byte [] bytes)
1070 StringWriter writer = new StringWriter ();
1071 int charsInLine = 0;
1073 StringBuilder sb = new StringBuilder("=", 3);
1074 byte equalSign = (byte)'=';
1077 foreach (byte i in bytes) {
1078 if (i > 127 || i == equalSign) {
1080 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1083 c = Convert.ToChar (i);
1084 if (c == '\r' || c == '\n') {
1092 charsInLine += curLen;
1093 if (charsInLine > 75) {
1094 writer.Write ("=\r\n");
1095 charsInLine = curLen;
1100 writer.Write (sb.ToString ());
1103 return writer.ToString ();
1105 private static string GetTransferEncodingName (TransferEncoding encoding)
1108 case TransferEncoding.QuotedPrintable:
1109 return "quoted-printable";
1110 case TransferEncoding.SevenBit:
1112 case TransferEncoding.Base64:
1119 RemoteCertificateValidationCallback callback = delegate (object sender,
1120 X509Certificate certificate,
1122 SslPolicyErrors sslPolicyErrors) {
1123 // honor any exciting callback defined on ServicePointManager
1124 if (ServicePointManager.ServerCertificateValidationCallback != null)
1125 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1126 // otherwise provide our own
1127 if (sslPolicyErrors != SslPolicyErrors.None)
1128 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1133 private void InitiateSecureConnection () {
1134 SmtpResponse response = SendCommand ("STARTTLS");
1136 if (IsError (response)) {
1137 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1141 ((NetworkStream) stream).ChangeToSSLSocket ();
1143 SslStream sslStream = new SslStream (stream, false, callback, null);
1144 CheckCancellation ();
1145 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1149 throw new SystemException ("You are using an incomplete System.dll build");
1153 void Authenticate ()
1155 string user = null, pass = null;
1157 if (UseDefaultCredentials) {
1158 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1159 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1160 } else if (Credentials != null) {
1161 user = Credentials.GetCredential (host, port, "smtp").UserName;
1162 pass = Credentials.GetCredential (host, port, "smtp").Password;
1167 Authenticate (user, pass);
1170 void Authenticate (string Username, string Password)
1172 // FIXME: use the proper AuthMech
1173 SmtpResponse status = SendCommand ("AUTH LOGIN");
1174 if (((int) status.StatusCode) != 334) {
1175 throw new SmtpException (status.StatusCode, status.Description);
1178 status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Username)));
1179 if (((int) status.StatusCode) != 334) {
1180 throw new SmtpException (status.StatusCode, status.Description);
1183 status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Password)));
1184 if (IsError (status)) {
1185 throw new SmtpException (status.StatusCode, status.Description);
1189 #endregion // Methods
1191 // The HeaderName struct is used to store constant string values representing mail headers.
1192 private struct HeaderName {
1193 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1194 public const string ContentType = "Content-Type";
1195 public const string Bcc = "Bcc";
1196 public const string Cc = "Cc";
1197 public const string From = "From";
1198 public const string Subject = "Subject";
1199 public const string To = "To";
1200 public const string MimeVersion = "MIME-Version";
1201 public const string MessageId = "Message-ID";
1202 public const string Priority = "Priority";
1203 public const string Importance = "Importance";
1204 public const string XPriority = "X-Priority";
1205 public const string Date = "Date";
1208 // This object encapsulates the status code and description of an SMTP response.
1209 private struct SmtpResponse {
1210 public SmtpStatusCode StatusCode;
1211 public string Description;
1213 public static SmtpResponse Parse (string line) {
1214 SmtpResponse response = new SmtpResponse ();
1216 if (line.Length < 4)
1217 throw new SmtpException ("Response is to short " +
1220 if ((line [3] != ' ') && (line [3] != '-'))
1221 throw new SmtpException ("Response format is wrong.(" +
1224 // parse the response code
1225 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1227 // set the raw response
1228 response.Description = line;
1235 class CCredentialsByHost : ICredentialsByHost
1237 public CCredentialsByHost (string userName, string password) {
1238 this.userName = userName;
1239 this.password = password;
1242 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1243 return new NetworkCredential (userName, password);
1246 private string userName;
1247 private string password;