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.
32 extern alias PrebuiltSystem;
36 using System.Collections.Generic;
37 using System.ComponentModel;
38 using System.Globalization;
41 using System.Net.Mime;
42 using System.Net.Sockets;
43 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
46 using System.Reflection;
47 using System.Net.Configuration;
48 using System.Configuration;
49 using System.Net.Security;
50 using System.Security.Authentication;
53 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
56 namespace System.Net.Mail {
57 public class SmtpClient
67 ICredentialsByHost credentials;
68 string pickupDirectoryLocation;
69 SmtpDeliveryMethod deliveryMethod;
72 X509CertificateCollection clientCertificates;
80 MailAddress defaultFrom;
82 MailMessage messageInProcess;
84 BackgroundWorker worker;
85 object user_async_state;
94 class CancellationException : Exception
99 Mutex mutex = new Mutex ();
110 public SmtpClient (string host)
115 public SmtpClient (string host, int port) {
116 #if CONFIGURATION_DEP
117 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
120 this.host = cfg.Network.Host;
121 this.port = cfg.Network.Port;
123 this.enableSsl = cfg.Network.EnableSsl;
125 TargetName = cfg.Network.TargetName;
126 if (this.TargetName == null)
127 TargetName = "SMTPSVC/" + (host != null ? host : "");
130 if (cfg.Network.UserName != null) {
131 string password = String.Empty;
133 if (cfg.Network.Password != null)
134 password = cfg.Network.Password;
136 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
139 if (!String.IsNullOrEmpty (cfg.From))
140 defaultFrom = new MailAddress (cfg.From);
143 // Just to eliminate the warning, this codepath does not end up in production.
147 if (!String.IsNullOrEmpty (host))
154 #endregion // Constructors
159 [MonoTODO("Client certificates not used")]
160 public X509CertificateCollection ClientCertificates {
162 if (clientCertificates == null)
163 clientCertificates = new X509CertificateCollection ();
164 return clientCertificates;
172 string TargetName { get; set; }
174 public ICredentialsByHost Credentials {
175 get { return credentials; }
182 public SmtpDeliveryMethod DeliveryMethod {
183 get { return deliveryMethod; }
186 deliveryMethod = value;
190 public bool EnableSsl {
191 get { return enableSsl; }
202 throw new ArgumentNullException ("value");
203 if (value.Length == 0)
204 throw new ArgumentException ("An empty string is not allowed.", "value");
210 public string PickupDirectoryLocation {
211 get { return pickupDirectoryLocation; }
212 set { pickupDirectoryLocation = value; }
219 throw new ArgumentOutOfRangeException ("value");
226 public ServicePoint ServicePoint {
227 get { throw new NotImplementedException (); }
231 get { return timeout; }
234 throw new ArgumentOutOfRangeException ("value");
240 public bool UseDefaultCredentials {
241 get { return false; }
242 [MonoNotSupported ("no DefaultCredential support in Mono")]
245 throw new NotImplementedException ("Default credentials are not supported");
250 #endregion // Properties
254 public event SendCompletedEventHandler SendCompleted;
260 public void Dispose ()
265 [MonoTODO ("Does nothing at the moment.")]
266 protected virtual void Dispose (bool disposing)
268 // 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 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
547 SendHeader (HeaderName.From, EncodeAddress(from));
548 SendHeader (HeaderName.To, EncodeAddresses(message.To));
549 if (message.CC.Count > 0)
550 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
551 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
553 foreach (string s in message.Headers.AllKeys)
554 SendHeader (s, message.Headers [s]);
556 AddPriorityHeader (message);
559 if (message.Attachments.Count > 0)
560 SendWithAttachments (message);
562 SendWithoutAttachments (message, null, false);
566 if (writer != null) writer.Close(); writer = null;
570 private void SendCore (MailMessage message)
575 if (IsError (status))
576 throw new SmtpException (status.StatusCode, status.Description);
580 // FIXME: parse the list of extensions so we don't bother wasting
581 // our time trying commands if they aren't supported.
582 status = SendCommand ("EHLO " + Dns.GetHostName ());
584 if (IsError (status)) {
585 status = SendCommand ("HELO " + Dns.GetHostName ());
587 if (IsError (status))
588 throw new SmtpException (status.StatusCode, status.Description);
590 // Parse ESMTP extensions
591 string extens = status.Description;
594 ParseExtensions (extens);
598 InitiateSecureConnection ();
600 writer = new StreamWriter (stream);
601 reader = new StreamReader (stream);
602 status = SendCommand ("EHLO " + Dns.GetHostName ());
604 if (IsError (status)) {
605 status = SendCommand ("HELO " + Dns.GetHostName ());
607 if (IsError (status))
608 throw new SmtpException (status.StatusCode, status.Description);
610 // Parse ESMTP extensions
611 string extens = status.Description;
613 ParseExtensions (extens);
617 if (authMechs != AuthMechs.None)
620 // The envelope sender: use 'Sender:' in preference of 'From:'
621 MailAddress sender = message.Sender;
623 sender = message.From;
625 sender = defaultFrom;
628 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
629 if (IsError (status)) {
630 throw new SmtpException (status.StatusCode, status.Description);
633 // Send RCPT TO: for all recipients
634 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
636 for (int i = 0; i < message.To.Count; i ++) {
637 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
638 if (IsError (status))
639 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
641 for (int i = 0; i < message.CC.Count; i ++) {
642 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
643 if (IsError (status))
644 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
646 for (int i = 0; i < message.Bcc.Count; i ++) {
647 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
648 if (IsError (status))
649 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
652 #if TARGET_JVM // List<T>.ToArray () is not supported
653 if (sfre.Count > 0) {
654 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
656 throw new SmtpFailedRecipientsException ("failed recipients", xs);
660 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
664 status = SendCommand ("DATA");
665 if (IsError (status))
666 throw new SmtpException (status.StatusCode, status.Description);
668 // Send message headers
669 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
670 // remove ':' from time zone offset (e.g. from "+01:00")
671 dt = dt.Remove (dt.Length - 3, 1);
672 SendHeader (HeaderName.Date, dt);
674 MailAddress from = message.From;
678 SendHeader (HeaderName.From, EncodeAddress (from));
679 SendHeader (HeaderName.To, EncodeAddresses (message.To));
680 if (message.CC.Count > 0)
681 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
682 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
686 switch (message.Priority){
687 case MailPriority.Normal:
691 case MailPriority.Low:
695 case MailPriority.High:
699 SendHeader ("Priority", v);
700 if (message.Sender != null)
701 SendHeader ("Sender", EncodeAddress (message.Sender));
702 if (message.ReplyToList.Count > 0)
703 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
706 foreach (string s in message.Headers.AllKeys)
707 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
709 foreach (string s in message.Headers.AllKeys)
710 SendHeader (s, message.Headers [s]);
713 AddPriorityHeader (message);
716 if (message.Attachments.Count > 0)
717 SendWithAttachments (message);
719 SendWithoutAttachments (message, null, false);
724 if (IsError (status))
725 throw new SmtpException (status.StatusCode, status.Description);
728 status = SendCommand ("QUIT");
729 } catch (System.IO.IOException) {
730 // We excuse server for the rude connection closing as a response to QUIT
734 public void Send (string from, string to, string subject, string body)
736 Send (new MailMessage (from, to, subject, body));
739 private void SendDot()
741 writer.Write(".\r\n");
745 private void SendData (string data)
747 if (String.IsNullOrEmpty (data)) {
748 writer.Write("\r\n");
753 StringReader sr = new StringReader (data);
755 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
756 while ((line = sr.ReadLine ()) != null) {
757 CheckCancellation ();
761 for (i = 0; i < line.Length; i++) {
765 if (i > 0 && i == line.Length) {
770 writer.Write ("\r\n");
775 public void SendAsync (MailMessage message, object userToken)
778 throw new InvalidOperationException ("Another SendAsync operation is in progress");
780 worker = new BackgroundWorker ();
781 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
783 user_async_state = ea.Argument;
785 } catch (Exception ex) {
790 worker.WorkerSupportsCancellation = true;
791 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
792 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
793 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
795 worker.RunWorkerAsync (userToken);
798 public void SendAsync (string from, string to, string subject, string body, object userToken)
800 SendAsync (new MailMessage (from, to, subject, body), userToken);
803 public void SendAsyncCancel ()
806 throw new InvalidOperationException ("SendAsync operation is not in progress");
807 worker.CancelAsync ();
810 private void AddPriorityHeader (MailMessage message) {
811 switch (message.Priority) {
812 case MailPriority.High:
813 SendHeader (HeaderName.Priority, "Urgent");
814 SendHeader (HeaderName.Importance, "high");
815 SendHeader (HeaderName.XPriority, "1");
817 case MailPriority.Low:
818 SendHeader (HeaderName.Priority, "Non-Urgent");
819 SendHeader (HeaderName.Importance, "low");
820 SendHeader (HeaderName.XPriority, "5");
825 private void SendSimpleBody (MailMessage message) {
826 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
827 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
828 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
829 SendData (string.Empty);
831 SendData (EncodeBody (message));
834 private void SendBodylessSingleAlternate (AlternateView av) {
835 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
836 if (av.TransferEncoding != TransferEncoding.SevenBit)
837 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
838 SendData (string.Empty);
840 SendData (EncodeBody (av));
843 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
845 if (message.Body == null && message.AlternateViews.Count == 1)
846 SendBodylessSingleAlternate (message.AlternateViews [0]);
847 else if (message.AlternateViews.Count > 0)
848 SendBodyWithAlternateViews (message, boundary, attachmentExists);
850 SendSimpleBody (message);
854 private void SendWithAttachments (MailMessage message) {
855 string boundary = GenerateBoundary ();
857 // first "multipart/mixed"
858 ContentType messageContentType = new ContentType ();
859 messageContentType.Boundary = boundary;
860 messageContentType.MediaType = "multipart/mixed";
861 messageContentType.CharSet = null;
863 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
864 SendData (String.Empty);
867 Attachment body = null;
869 if (message.AlternateViews.Count > 0)
870 SendWithoutAttachments (message, boundary, true);
872 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
873 message.Attachments.Insert (0, body);
877 SendAttachments (message, body, boundary);
880 message.Attachments.Remove (body);
883 EndSection (boundary);
886 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
888 AlternateViewCollection alternateViews = message.AlternateViews;
890 string inner_boundary = GenerateBoundary ();
892 ContentType messageContentType = new ContentType ();
893 messageContentType.Boundary = inner_boundary;
894 messageContentType.MediaType = "multipart/alternative";
896 if (!attachmentExists) {
897 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
898 SendData (String.Empty);
902 AlternateView body = null;
903 if (message.Body != null) {
904 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
905 alternateViews.Insert (0, body);
906 StartSection (boundary, messageContentType);
910 // alternate view sections
911 foreach (AlternateView av in alternateViews) {
913 string alt_boundary = null;
914 ContentType contentType;
915 if (av.LinkedResources.Count > 0) {
916 alt_boundary = GenerateBoundary ();
917 contentType = new ContentType ("multipart/related");
918 contentType.Boundary = alt_boundary;
920 contentType.Parameters ["type"] = av.ContentType.ToString ();
921 StartSection (inner_boundary, contentType);
922 StartSection (alt_boundary, av.ContentType, av);
924 contentType = new ContentType (av.ContentType.ToString ());
925 StartSection (inner_boundary, contentType, av);
928 switch (av.TransferEncoding) {
929 case TransferEncoding.Base64:
930 byte [] content = new byte [av.ContentStream.Length];
931 av.ContentStream.Read (content, 0, content.Length);
933 SendData (Convert.ToBase64String (content));
935 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
938 case TransferEncoding.QuotedPrintable:
939 byte [] bytes = new byte [av.ContentStream.Length];
940 av.ContentStream.Read (bytes, 0, bytes.Length);
941 SendData (ToQuotedPrintable (bytes));
943 case TransferEncoding.SevenBit:
944 case TransferEncoding.Unknown:
945 content = new byte [av.ContentStream.Length];
946 av.ContentStream.Read (content, 0, content.Length);
947 SendData (Encoding.ASCII.GetString (content));
951 if (av.LinkedResources.Count > 0) {
952 SendLinkedResources (message, av.LinkedResources, alt_boundary);
953 EndSection (alt_boundary);
956 if (!attachmentExists)
957 SendData (string.Empty);
962 alternateViews.Remove (body);
964 EndSection (inner_boundary);
967 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
969 foreach (LinkedResource lr in resources) {
970 StartSection (boundary, lr.ContentType, lr);
972 switch (lr.TransferEncoding) {
973 case TransferEncoding.Base64:
974 byte [] content = new byte [lr.ContentStream.Length];
975 lr.ContentStream.Read (content, 0, content.Length);
977 SendData (Convert.ToBase64String (content));
979 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
982 case TransferEncoding.QuotedPrintable:
983 byte [] bytes = new byte [lr.ContentStream.Length];
984 lr.ContentStream.Read (bytes, 0, bytes.Length);
985 SendData (ToQuotedPrintable (bytes));
987 case TransferEncoding.SevenBit:
988 case TransferEncoding.Unknown:
989 content = new byte [lr.ContentStream.Length];
990 lr.ContentStream.Read (content, 0, content.Length);
991 SendData (Encoding.ASCII.GetString (content));
997 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
998 foreach (Attachment att in message.Attachments) {
999 ContentType contentType = new ContentType (att.ContentType.ToString ());
1000 if (att.Name != null) {
1001 contentType.Name = att.Name;
1002 if (att.NameEncoding != null)
1003 contentType.CharSet = att.NameEncoding.HeaderName;
1004 att.ContentDisposition.FileName = att.Name;
1006 StartSection (boundary, contentType, att, att != body);
1008 byte [] content = new byte [att.ContentStream.Length];
1009 att.ContentStream.Read (content, 0, content.Length);
1010 switch (att.TransferEncoding) {
1011 case TransferEncoding.Base64:
1013 SendData (Convert.ToBase64String (content));
1015 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1018 case TransferEncoding.QuotedPrintable:
1019 SendData (ToQuotedPrintable (content));
1021 case TransferEncoding.SevenBit:
1022 case TransferEncoding.Unknown:
1023 SendData (Encoding.ASCII.GetString (content));
1027 SendData (string.Empty);
1031 private SmtpResponse SendCommand (string command)
1033 writer.Write (command);
1034 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1035 writer.Write ("\r\n");
1040 private void SendHeader (string name, string value)
1042 SendData (String.Format ("{0}: {1}", name, value));
1045 private void StartSection (string section, ContentType sectionContentType)
1047 SendData (String.Format ("--{0}", section));
1048 SendHeader ("content-type", sectionContentType.ToString ());
1049 SendData (string.Empty);
1052 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1054 SendData (String.Format ("--{0}", section));
1055 SendHeader ("content-type", sectionContentType.ToString ());
1056 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1057 if (!string.IsNullOrEmpty (att.ContentId))
1058 SendHeader("content-ID", "<" + att.ContentId + ">");
1059 SendData (string.Empty);
1062 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1063 SendData (String.Format ("--{0}", section));
1064 if (!string.IsNullOrEmpty (att.ContentId))
1065 SendHeader("content-ID", "<" + att.ContentId + ">");
1066 SendHeader ("content-type", sectionContentType.ToString ());
1067 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1068 if (sendDisposition)
1069 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1070 SendData (string.Empty);
1073 // use proper encoding to escape input
1074 private string ToQuotedPrintable (string input, Encoding enc)
1076 byte [] bytes = enc.GetBytes (input);
1077 return ToQuotedPrintable (bytes);
1080 private string ToQuotedPrintable (byte [] bytes)
1082 StringWriter writer = new StringWriter ();
1083 int charsInLine = 0;
1085 StringBuilder sb = new StringBuilder("=", 3);
1086 byte equalSign = (byte)'=';
1089 foreach (byte i in bytes) {
1090 if (i > 127 || i == equalSign) {
1092 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1095 c = Convert.ToChar (i);
1096 if (c == '\r' || c == '\n') {
1104 charsInLine += curLen;
1105 if (charsInLine > 75) {
1106 writer.Write ("=\r\n");
1107 charsInLine = curLen;
1112 writer.Write (sb.ToString ());
1115 return writer.ToString ();
1117 private static string GetTransferEncodingName (TransferEncoding encoding)
1120 case TransferEncoding.QuotedPrintable:
1121 return "quoted-printable";
1122 case TransferEncoding.SevenBit:
1124 case TransferEncoding.Base64:
1131 RemoteCertificateValidationCallback callback = delegate (object sender,
1132 X509Certificate certificate,
1134 SslPolicyErrors sslPolicyErrors) {
1135 // honor any exciting callback defined on ServicePointManager
1136 if (ServicePointManager.ServerCertificateValidationCallback != null)
1137 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1138 // otherwise provide our own
1139 if (sslPolicyErrors != SslPolicyErrors.None)
1140 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1145 private void InitiateSecureConnection () {
1146 SmtpResponse response = SendCommand ("STARTTLS");
1148 if (IsError (response)) {
1149 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1153 ((NetworkStream) stream).ChangeToSSLSocket ();
1155 SslStream sslStream = new SslStream (stream, false, callback, null);
1156 CheckCancellation ();
1157 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1161 throw new SystemException ("You are using an incomplete System.dll build");
1165 void Authenticate ()
1167 string user = null, pass = null;
1169 if (UseDefaultCredentials) {
1170 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1171 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1172 } else if (Credentials != null) {
1173 user = Credentials.GetCredential (host, port, "smtp").UserName;
1174 pass = Credentials.GetCredential (host, port, "smtp").Password;
1179 Authenticate (user, pass);
1182 void CheckStatus (SmtpResponse status, int i)
1184 if (((int) status.StatusCode) != i)
1185 throw new SmtpException (status.StatusCode, status.Description);
1188 void ThrowIfError (SmtpResponse status)
1190 if (IsError (status))
1191 throw new SmtpException (status.StatusCode, status.Description);
1194 void Authenticate (string user, string password)
1196 if (authMechs == AuthMechs.None)
1199 SmtpResponse status;
1201 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1202 status = SendCommand ("AUTH DIGEST-MD5");
1203 CheckStatus (status, 334);
1204 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1205 Console.WriteLine ("CHALLENGE: {0}", challenge);
1206 DigestSession session = new DigestSession ();
1207 session.Parse (false, challenge);
1208 string response = session.Authenticate (this, user, password);
1209 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1210 CheckStatus (status, 235);
1212 if ((authMechs & AuthMechs.Login) != 0) {
1213 status = SendCommand ("AUTH LOGIN");
1214 CheckStatus (status, 334);
1215 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1216 CheckStatus (status, 334);
1217 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1218 CheckStatus (status, 235);
1219 } else if ((authMechs & AuthMechs.Plain) != 0) {
1220 string s = String.Format ("\0{0}\0{1}", user, password);
1221 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1222 status = SendCommand ("AUTH PLAIN " + s);
1223 CheckStatus (status, 235);
1225 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1229 #endregion // Methods
1231 // The HeaderName struct is used to store constant string values representing mail headers.
1232 private struct HeaderName {
1233 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1234 public const string ContentType = "Content-Type";
1235 public const string Bcc = "Bcc";
1236 public const string Cc = "Cc";
1237 public const string From = "From";
1238 public const string Subject = "Subject";
1239 public const string To = "To";
1240 public const string MimeVersion = "MIME-Version";
1241 public const string MessageId = "Message-ID";
1242 public const string Priority = "Priority";
1243 public const string Importance = "Importance";
1244 public const string XPriority = "X-Priority";
1245 public const string Date = "Date";
1248 // This object encapsulates the status code and description of an SMTP response.
1249 private struct SmtpResponse {
1250 public SmtpStatusCode StatusCode;
1251 public string Description;
1253 public static SmtpResponse Parse (string line) {
1254 SmtpResponse response = new SmtpResponse ();
1256 if (line.Length < 4)
1257 throw new SmtpException ("Response is to short " +
1260 if ((line [3] != ' ') && (line [3] != '-'))
1261 throw new SmtpException ("Response format is wrong.(" +
1264 // parse the response code
1265 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1267 // set the raw response
1268 response.Description = line;
1275 class CCredentialsByHost : ICredentialsByHost
1277 public CCredentialsByHost (string userName, string password) {
1278 this.userName = userName;
1279 this.password = password;
1282 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1283 return new NetworkCredential (userName, password);
1286 private string userName;
1287 private string password;