2 // System.Net.Mail.SmtpClient.cs
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2004
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 #if MONOTOUCH || MONODROID
34 using System.Security.Cryptography.X509Certificates;
36 extern alias PrebuiltSystem;
37 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
38 using System.Security.Cryptography.X509Certificates;
44 using System.Collections.Generic;
45 using System.ComponentModel;
46 using System.Globalization;
49 using System.Net.Mime;
50 using System.Net.Sockets;
52 using System.Threading;
53 using System.Reflection;
54 using System.Net.Configuration;
55 using System.Configuration;
56 using System.Net.Security;
57 using System.Security.Authentication;
59 using System.Threading.Tasks;
62 namespace System.Net.Mail {
63 public class SmtpClient
73 ICredentialsByHost credentials;
74 string pickupDirectoryLocation;
75 SmtpDeliveryMethod deliveryMethod;
78 X509CertificateCollection clientCertificates;
86 MailAddress defaultFrom;
88 MailMessage messageInProcess;
90 BackgroundWorker worker;
91 object user_async_state;
100 class CancellationException : Exception
105 Mutex mutex = new Mutex ();
116 public SmtpClient (string host)
121 public SmtpClient (string host, int port) {
122 #if CONFIGURATION_DEP
123 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
126 this.host = cfg.Network.Host;
127 this.port = cfg.Network.Port;
129 this.enableSsl = cfg.Network.EnableSsl;
131 TargetName = cfg.Network.TargetName;
132 if (this.TargetName == null)
133 TargetName = "SMTPSVC/" + (host != null ? host : "");
136 if (cfg.Network.UserName != null) {
137 string password = String.Empty;
139 if (cfg.Network.Password != null)
140 password = cfg.Network.Password;
142 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
145 if (!String.IsNullOrEmpty (cfg.From))
146 defaultFrom = new MailAddress (cfg.From);
149 // Just to eliminate the warning, this codepath does not end up in production.
153 if (!String.IsNullOrEmpty (host))
158 else if (this.port == 0)
162 #endregion // Constructors
167 [MonoTODO("Client certificates not used")]
168 public X509CertificateCollection ClientCertificates {
170 if (clientCertificates == null)
171 clientCertificates = new X509CertificateCollection ();
172 return clientCertificates;
180 string TargetName { get; set; }
182 public ICredentialsByHost Credentials {
183 get { return credentials; }
190 public SmtpDeliveryMethod DeliveryMethod {
191 get { return deliveryMethod; }
194 deliveryMethod = value;
198 public bool EnableSsl {
199 get { return enableSsl; }
210 throw new ArgumentNullException ("value");
211 if (value.Length == 0)
212 throw new ArgumentException ("An empty string is not allowed.", "value");
218 public string PickupDirectoryLocation {
219 get { return pickupDirectoryLocation; }
220 set { pickupDirectoryLocation = value; }
227 throw new ArgumentOutOfRangeException ("value");
234 public ServicePoint ServicePoint {
235 get { throw new NotImplementedException (); }
239 get { return timeout; }
242 throw new ArgumentOutOfRangeException ("value");
248 public bool UseDefaultCredentials {
249 get { return false; }
250 [MonoNotSupported ("no DefaultCredential support in Mono")]
253 throw new NotImplementedException ("Default credentials are not supported");
258 #endregion // Properties
262 public event SendCompletedEventHandler SendCompleted;
268 public void Dispose ()
273 [MonoTODO ("Does nothing at the moment.")]
274 protected virtual void Dispose (bool disposing)
276 // TODO: We should close all the connections and abort any async operations here
279 private void CheckState ()
281 if (messageInProcess != null)
282 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
285 private static string EncodeAddress(MailAddress address)
287 if (!String.IsNullOrEmpty (address.DisplayName)) {
288 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
289 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
291 return address.ToString ();
294 private static string EncodeAddresses(MailAddressCollection addresses)
296 StringBuilder sb = new StringBuilder();
298 foreach (MailAddress address in addresses) {
302 sb.Append(EncodeAddress(address));
305 return sb.ToString();
308 private string EncodeSubjectRFC2047 (MailMessage message)
310 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
313 private string EncodeBody (MailMessage message)
315 string body = message.Body;
316 Encoding encoding = message.BodyEncoding;
318 switch (message.ContentTransferEncoding) {
319 case TransferEncoding.SevenBit:
321 case TransferEncoding.Base64:
322 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
324 return ToQuotedPrintable (body, encoding);
328 private string EncodeBody (AlternateView av)
330 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
332 byte [] bytes = new byte [av.ContentStream.Length];
333 av.ContentStream.Read (bytes, 0, bytes.Length);
336 switch (av.TransferEncoding) {
337 case TransferEncoding.SevenBit:
338 return Encoding.ASCII.GetString (bytes);
339 case TransferEncoding.Base64:
340 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
342 return ToQuotedPrintable (bytes);
347 private void EndSection (string section)
349 SendData (String.Format ("--{0}--", section));
350 SendData (string.Empty);
353 private string GenerateBoundary ()
355 string output = GenerateBoundary (boundaryIndex);
360 private static string GenerateBoundary (int index)
362 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
365 private bool IsError (SmtpResponse status)
367 return ((int) status.StatusCode) >= 400;
370 protected void OnSendCompleted (AsyncCompletedEventArgs e)
373 if (SendCompleted != null)
374 SendCompleted (this, e);
377 user_async_state = null;
381 private void CheckCancellation ()
383 if (worker != null && worker.CancellationPending)
384 throw new CancellationException ();
387 private SmtpResponse Read () {
388 byte [] buffer = new byte [512];
390 bool lastLine = false;
393 CheckCancellation ();
395 int readLength = stream.Read (buffer, position, buffer.Length - position);
396 if (readLength > 0) {
397 int available = position + readLength - 1;
398 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
399 for (int index = available - 3; ; index--) {
400 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
401 lastLine = buffer [index + 4] == ' ';
407 position += readLength;
409 // check if buffer is full
410 if (position == buffer.Length) {
411 byte [] newBuffer = new byte [buffer.Length * 2];
412 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
422 Encoding encoding = new ASCIIEncoding ();
424 string line = encoding.GetString (buffer, 0, position - 1);
426 // parse the line to the lastResponse object
427 SmtpResponse response = SmtpResponse.Parse (line);
431 throw new System.IO.IOException ("Connection closed");
435 void ResetExtensions()
437 authMechs = AuthMechs.None;
440 void ParseExtensions (string extens)
442 string[] parts = extens.Split ('\n');
444 foreach (string part in parts) {
448 string start = part.Substring (4);
449 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
450 string[] options = start.Split (' ');
451 for (int k = 1; k < options.Length; k++) {
452 string option = options[k].Trim();
453 // GSSAPI, KERBEROS_V4, NTLM not supported
457 authMechs |= AuthMechs.CramMD5;
460 authMechs |= AuthMechs.DigestMD5;
464 authMechs |= AuthMechs.Login;
467 authMechs |= AuthMechs.Plain;
475 public void Send (MailMessage message)
478 throw new ArgumentNullException ("message");
480 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
481 throw new InvalidOperationException ("The SMTP host was not specified");
482 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
483 throw new NotSupportedException("IIS delivery is not supported");
488 // Block while sending
491 messageInProcess = message;
492 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
493 SendToFile (message);
495 SendInternal (message);
496 } catch (CancellationException) {
497 // This exception is introduced for convenient cancellation process.
498 } catch (SmtpException) {
500 } catch (Exception ex) {
501 throw new SmtpException ("Message could not be sent.", ex);
503 // Release the mutex to allow other threads access
504 mutex.ReleaseMutex ();
505 messageInProcess = null;
509 private void SendInternal (MailMessage message)
511 CheckCancellation ();
514 client = new TcpClient (host, port);
515 stream = client.GetStream ();
516 // FIXME: this StreamWriter creation is bogus.
517 // It expects as if a Stream were able to switch to SSL
518 // mode (such behavior is only in Mainsoft Socket API).
519 writer = new StreamWriter (stream);
520 reader = new StreamReader (stream);
535 // FIXME: simple implementation, could be brushed up.
536 private void SendToFile (MailMessage message)
538 if (!Path.IsPathRooted (pickupDirectoryLocation))
539 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
541 string filename = Path.Combine (pickupDirectoryLocation,
542 Guid.NewGuid() + ".eml");
545 writer = new StreamWriter(filename);
547 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
548 // For all we know, defaultFrom may be the envelope sender
549 // For now, we are no worse than some versions of .NET
550 MailAddress from = message.From;
554 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
555 SendHeader (HeaderName.From, EncodeAddress(from));
556 SendHeader (HeaderName.To, EncodeAddresses(message.To));
557 if (message.CC.Count > 0)
558 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
559 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
561 foreach (string s in message.Headers.AllKeys)
562 SendHeader (s, message.Headers [s]);
564 AddPriorityHeader (message);
567 if (message.Attachments.Count > 0)
568 SendWithAttachments (message);
570 SendWithoutAttachments (message, null, false);
574 if (writer != null) writer.Close(); writer = null;
578 private void SendCore (MailMessage message)
583 if (IsError (status))
584 throw new SmtpException (status.StatusCode, status.Description);
588 // FIXME: parse the list of extensions so we don't bother wasting
589 // our time trying commands if they aren't supported.
590 status = SendCommand ("EHLO " + Dns.GetHostName ());
592 if (IsError (status)) {
593 status = SendCommand ("HELO " + Dns.GetHostName ());
595 if (IsError (status))
596 throw new SmtpException (status.StatusCode, status.Description);
598 // Parse ESMTP extensions
599 string extens = status.Description;
602 ParseExtensions (extens);
606 InitiateSecureConnection ();
608 writer = new StreamWriter (stream);
609 reader = new StreamReader (stream);
610 status = SendCommand ("EHLO " + Dns.GetHostName ());
612 if (IsError (status)) {
613 status = SendCommand ("HELO " + Dns.GetHostName ());
615 if (IsError (status))
616 throw new SmtpException (status.StatusCode, status.Description);
618 // Parse ESMTP extensions
619 string extens = status.Description;
621 ParseExtensions (extens);
625 if (authMechs != AuthMechs.None)
628 // The envelope sender: use 'Sender:' in preference of 'From:'
629 MailAddress sender = message.Sender;
631 sender = message.From;
633 sender = defaultFrom;
636 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
637 if (IsError (status)) {
638 throw new SmtpException (status.StatusCode, status.Description);
641 // Send RCPT TO: for all recipients
642 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
644 for (int i = 0; i < message.To.Count; i ++) {
645 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
646 if (IsError (status))
647 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
649 for (int i = 0; i < message.CC.Count; i ++) {
650 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
651 if (IsError (status))
652 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
654 for (int i = 0; i < message.Bcc.Count; i ++) {
655 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
656 if (IsError (status))
657 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
660 #if TARGET_JVM // List<T>.ToArray () is not supported
661 if (sfre.Count > 0) {
662 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
664 throw new SmtpFailedRecipientsException ("failed recipients", xs);
668 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
672 status = SendCommand ("DATA");
673 if (IsError (status))
674 throw new SmtpException (status.StatusCode, status.Description);
676 // Send message headers
677 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
678 // remove ':' from time zone offset (e.g. from "+01:00")
679 dt = dt.Remove (dt.Length - 3, 1);
680 SendHeader (HeaderName.Date, dt);
682 MailAddress from = message.From;
686 SendHeader (HeaderName.From, EncodeAddress (from));
687 SendHeader (HeaderName.To, EncodeAddresses (message.To));
688 if (message.CC.Count > 0)
689 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
690 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
694 switch (message.Priority){
695 case MailPriority.Normal:
699 case MailPriority.Low:
703 case MailPriority.High:
707 SendHeader ("Priority", v);
708 if (message.Sender != null)
709 SendHeader ("Sender", EncodeAddress (message.Sender));
710 if (message.ReplyToList.Count > 0)
711 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
714 foreach (string s in message.Headers.AllKeys)
715 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
717 foreach (string s in message.Headers.AllKeys)
718 SendHeader (s, message.Headers [s]);
721 AddPriorityHeader (message);
724 if (message.Attachments.Count > 0)
725 SendWithAttachments (message);
727 SendWithoutAttachments (message, null, false);
732 if (IsError (status))
733 throw new SmtpException (status.StatusCode, status.Description);
736 status = SendCommand ("QUIT");
737 } catch (System.IO.IOException) {
738 // We excuse server for the rude connection closing as a response to QUIT
742 public void Send (string from, string to, string subject, string body)
744 Send (new MailMessage (from, to, subject, body));
748 public Task SendMailAsync (MailMessage message)
750 var tcs = new TaskCompletionSource<object> ();
751 SendCompletedEventHandler handler = null;
752 handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
753 SendCompleted += handler;
754 SendAsync (message, tcs);
758 public Task SendMailAsync (string from, string recipients, string subject, string body)
760 return SendMailAsync (new MailMessage (from, recipients, subject, body));
763 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
765 if (handler != e.UserState)
768 client.SendCompleted -= handler;
770 if (e.Error != null) {
771 source.SetException (e.Error);
776 source.SetCanceled ();
780 source.SetResult (null);
784 private void SendDot()
786 writer.Write(".\r\n");
790 private void SendData (string data)
792 if (String.IsNullOrEmpty (data)) {
793 writer.Write("\r\n");
798 StringReader sr = new StringReader (data);
800 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
801 while ((line = sr.ReadLine ()) != null) {
802 CheckCancellation ();
806 for (i = 0; i < line.Length; i++) {
810 if (i > 0 && i == line.Length) {
815 writer.Write ("\r\n");
820 public void SendAsync (MailMessage message, object userToken)
823 throw new InvalidOperationException ("Another SendAsync operation is in progress");
825 worker = new BackgroundWorker ();
826 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
828 user_async_state = ea.Argument;
830 } catch (Exception ex) {
835 worker.WorkerSupportsCancellation = true;
836 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
837 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
838 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
840 worker.RunWorkerAsync (userToken);
843 public void SendAsync (string from, string to, string subject, string body, object userToken)
845 SendAsync (new MailMessage (from, to, subject, body), userToken);
848 public void SendAsyncCancel ()
851 throw new InvalidOperationException ("SendAsync operation is not in progress");
852 worker.CancelAsync ();
855 private void AddPriorityHeader (MailMessage message) {
856 switch (message.Priority) {
857 case MailPriority.High:
858 SendHeader (HeaderName.Priority, "Urgent");
859 SendHeader (HeaderName.Importance, "high");
860 SendHeader (HeaderName.XPriority, "1");
862 case MailPriority.Low:
863 SendHeader (HeaderName.Priority, "Non-Urgent");
864 SendHeader (HeaderName.Importance, "low");
865 SendHeader (HeaderName.XPriority, "5");
870 private void SendSimpleBody (MailMessage message) {
871 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
872 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
873 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
874 SendData (string.Empty);
876 SendData (EncodeBody (message));
879 private void SendBodylessSingleAlternate (AlternateView av) {
880 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
881 if (av.TransferEncoding != TransferEncoding.SevenBit)
882 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
883 SendData (string.Empty);
885 SendData (EncodeBody (av));
888 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
890 if (message.Body == null && message.AlternateViews.Count == 1)
891 SendBodylessSingleAlternate (message.AlternateViews [0]);
892 else if (message.AlternateViews.Count > 0)
893 SendBodyWithAlternateViews (message, boundary, attachmentExists);
895 SendSimpleBody (message);
899 private void SendWithAttachments (MailMessage message) {
900 string boundary = GenerateBoundary ();
902 // first "multipart/mixed"
903 ContentType messageContentType = new ContentType ();
904 messageContentType.Boundary = boundary;
905 messageContentType.MediaType = "multipart/mixed";
906 messageContentType.CharSet = null;
908 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
909 SendData (String.Empty);
912 Attachment body = null;
914 if (message.AlternateViews.Count > 0)
915 SendWithoutAttachments (message, boundary, true);
917 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
918 message.Attachments.Insert (0, body);
922 SendAttachments (message, body, boundary);
925 message.Attachments.Remove (body);
928 EndSection (boundary);
931 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
933 AlternateViewCollection alternateViews = message.AlternateViews;
935 string inner_boundary = GenerateBoundary ();
937 ContentType messageContentType = new ContentType ();
938 messageContentType.Boundary = inner_boundary;
939 messageContentType.MediaType = "multipart/alternative";
941 if (!attachmentExists) {
942 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
943 SendData (String.Empty);
947 AlternateView body = null;
948 if (message.Body != null) {
949 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
950 alternateViews.Insert (0, body);
951 StartSection (boundary, messageContentType);
955 // alternate view sections
956 foreach (AlternateView av in alternateViews) {
958 string alt_boundary = null;
959 ContentType contentType;
960 if (av.LinkedResources.Count > 0) {
961 alt_boundary = GenerateBoundary ();
962 contentType = new ContentType ("multipart/related");
963 contentType.Boundary = alt_boundary;
965 contentType.Parameters ["type"] = av.ContentType.ToString ();
966 StartSection (inner_boundary, contentType);
967 StartSection (alt_boundary, av.ContentType, av);
969 contentType = new ContentType (av.ContentType.ToString ());
970 StartSection (inner_boundary, contentType, av);
973 switch (av.TransferEncoding) {
974 case TransferEncoding.Base64:
975 byte [] content = new byte [av.ContentStream.Length];
976 av.ContentStream.Read (content, 0, content.Length);
978 SendData (Convert.ToBase64String (content));
980 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
983 case TransferEncoding.QuotedPrintable:
984 byte [] bytes = new byte [av.ContentStream.Length];
985 av.ContentStream.Read (bytes, 0, bytes.Length);
986 SendData (ToQuotedPrintable (bytes));
988 case TransferEncoding.SevenBit:
989 case TransferEncoding.Unknown:
990 content = new byte [av.ContentStream.Length];
991 av.ContentStream.Read (content, 0, content.Length);
992 SendData (Encoding.ASCII.GetString (content));
996 if (av.LinkedResources.Count > 0) {
997 SendLinkedResources (message, av.LinkedResources, alt_boundary);
998 EndSection (alt_boundary);
1001 if (!attachmentExists)
1002 SendData (string.Empty);
1007 alternateViews.Remove (body);
1009 EndSection (inner_boundary);
1012 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
1014 foreach (LinkedResource lr in resources) {
1015 StartSection (boundary, lr.ContentType, lr);
1017 switch (lr.TransferEncoding) {
1018 case TransferEncoding.Base64:
1019 byte [] content = new byte [lr.ContentStream.Length];
1020 lr.ContentStream.Read (content, 0, content.Length);
1022 SendData (Convert.ToBase64String (content));
1024 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1027 case TransferEncoding.QuotedPrintable:
1028 byte [] bytes = new byte [lr.ContentStream.Length];
1029 lr.ContentStream.Read (bytes, 0, bytes.Length);
1030 SendData (ToQuotedPrintable (bytes));
1032 case TransferEncoding.SevenBit:
1033 case TransferEncoding.Unknown:
1034 content = new byte [lr.ContentStream.Length];
1035 lr.ContentStream.Read (content, 0, content.Length);
1036 SendData (Encoding.ASCII.GetString (content));
1042 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1043 foreach (Attachment att in message.Attachments) {
1044 ContentType contentType = new ContentType (att.ContentType.ToString ());
1045 if (att.Name != null) {
1046 contentType.Name = att.Name;
1047 if (att.NameEncoding != null)
1048 contentType.CharSet = att.NameEncoding.HeaderName;
1049 att.ContentDisposition.FileName = att.Name;
1051 StartSection (boundary, contentType, att, att != body);
1053 byte [] content = new byte [att.ContentStream.Length];
1054 att.ContentStream.Read (content, 0, content.Length);
1055 switch (att.TransferEncoding) {
1056 case TransferEncoding.Base64:
1058 SendData (Convert.ToBase64String (content));
1060 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1063 case TransferEncoding.QuotedPrintable:
1064 SendData (ToQuotedPrintable (content));
1066 case TransferEncoding.SevenBit:
1067 case TransferEncoding.Unknown:
1068 SendData (Encoding.ASCII.GetString (content));
1072 SendData (string.Empty);
1076 private SmtpResponse SendCommand (string command)
1078 writer.Write (command);
1079 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1080 writer.Write ("\r\n");
1085 private void SendHeader (string name, string value)
1087 SendData (String.Format ("{0}: {1}", name, value));
1090 private void StartSection (string section, ContentType sectionContentType)
1092 SendData (String.Format ("--{0}", section));
1093 SendHeader ("content-type", sectionContentType.ToString ());
1094 SendData (string.Empty);
1097 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1099 SendData (String.Format ("--{0}", section));
1100 SendHeader ("content-type", sectionContentType.ToString ());
1101 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1102 if (!string.IsNullOrEmpty (att.ContentId))
1103 SendHeader("content-ID", "<" + att.ContentId + ">");
1104 SendData (string.Empty);
1107 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1108 SendData (String.Format ("--{0}", section));
1109 if (!string.IsNullOrEmpty (att.ContentId))
1110 SendHeader("content-ID", "<" + att.ContentId + ">");
1111 SendHeader ("content-type", sectionContentType.ToString ());
1112 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1113 if (sendDisposition)
1114 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1115 SendData (string.Empty);
1118 // use proper encoding to escape input
1119 private string ToQuotedPrintable (string input, Encoding enc)
1121 byte [] bytes = enc.GetBytes (input);
1122 return ToQuotedPrintable (bytes);
1125 private string ToQuotedPrintable (byte [] bytes)
1127 StringWriter writer = new StringWriter ();
1128 int charsInLine = 0;
1130 StringBuilder sb = new StringBuilder("=", 3);
1131 byte equalSign = (byte)'=';
1134 foreach (byte i in bytes) {
1135 if (i > 127 || i == equalSign) {
1137 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1140 c = Convert.ToChar (i);
1141 if (c == '\r' || c == '\n') {
1149 charsInLine += curLen;
1150 if (charsInLine > 75) {
1151 writer.Write ("=\r\n");
1152 charsInLine = curLen;
1157 writer.Write (sb.ToString ());
1160 return writer.ToString ();
1162 private static string GetTransferEncodingName (TransferEncoding encoding)
1165 case TransferEncoding.QuotedPrintable:
1166 return "quoted-printable";
1167 case TransferEncoding.SevenBit:
1169 case TransferEncoding.Base64:
1176 RemoteCertificateValidationCallback callback = delegate (object sender,
1177 X509Certificate certificate,
1179 SslPolicyErrors sslPolicyErrors) {
1180 // honor any exciting callback defined on ServicePointManager
1181 if (ServicePointManager.ServerCertificateValidationCallback != null)
1182 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1183 // otherwise provide our own
1184 if (sslPolicyErrors != SslPolicyErrors.None)
1185 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1190 private void InitiateSecureConnection () {
1191 SmtpResponse response = SendCommand ("STARTTLS");
1193 if (IsError (response)) {
1194 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1198 ((NetworkStream) stream).ChangeToSSLSocket ();
1200 SslStream sslStream = new SslStream (stream, false, callback, null);
1201 CheckCancellation ();
1202 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1206 throw new SystemException ("You are using an incomplete System.dll build");
1210 void Authenticate ()
1212 string user = null, pass = null;
1214 if (UseDefaultCredentials) {
1215 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1216 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1217 } else if (Credentials != null) {
1218 user = Credentials.GetCredential (host, port, "smtp").UserName;
1219 pass = Credentials.GetCredential (host, port, "smtp").Password;
1224 Authenticate (user, pass);
1227 void CheckStatus (SmtpResponse status, int i)
1229 if (((int) status.StatusCode) != i)
1230 throw new SmtpException (status.StatusCode, status.Description);
1233 void ThrowIfError (SmtpResponse status)
1235 if (IsError (status))
1236 throw new SmtpException (status.StatusCode, status.Description);
1239 void Authenticate (string user, string password)
1241 if (authMechs == AuthMechs.None)
1244 SmtpResponse status;
1246 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1247 status = SendCommand ("AUTH DIGEST-MD5");
1248 CheckStatus (status, 334);
1249 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1250 Console.WriteLine ("CHALLENGE: {0}", challenge);
1251 DigestSession session = new DigestSession ();
1252 session.Parse (false, challenge);
1253 string response = session.Authenticate (this, user, password);
1254 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1255 CheckStatus (status, 235);
1257 if ((authMechs & AuthMechs.Login) != 0) {
1258 status = SendCommand ("AUTH LOGIN");
1259 CheckStatus (status, 334);
1260 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1261 CheckStatus (status, 334);
1262 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1263 CheckStatus (status, 235);
1264 } else if ((authMechs & AuthMechs.Plain) != 0) {
1265 string s = String.Format ("\0{0}\0{1}", user, password);
1266 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1267 status = SendCommand ("AUTH PLAIN " + s);
1268 CheckStatus (status, 235);
1270 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1274 #endregion // Methods
1276 // The HeaderName struct is used to store constant string values representing mail headers.
1277 private struct HeaderName {
1278 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1279 public const string ContentType = "Content-Type";
1280 public const string Bcc = "Bcc";
1281 public const string Cc = "Cc";
1282 public const string From = "From";
1283 public const string Subject = "Subject";
1284 public const string To = "To";
1285 public const string MimeVersion = "MIME-Version";
1286 public const string MessageId = "Message-ID";
1287 public const string Priority = "Priority";
1288 public const string Importance = "Importance";
1289 public const string XPriority = "X-Priority";
1290 public const string Date = "Date";
1293 // This object encapsulates the status code and description of an SMTP response.
1294 private struct SmtpResponse {
1295 public SmtpStatusCode StatusCode;
1296 public string Description;
1298 public static SmtpResponse Parse (string line) {
1299 SmtpResponse response = new SmtpResponse ();
1301 if (line.Length < 4)
1302 throw new SmtpException ("Response is to short " +
1305 if ((line [3] != ' ') && (line [3] != '-'))
1306 throw new SmtpException ("Response format is wrong.(" +
1309 // parse the response code
1310 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1312 // set the raw response
1313 response.Description = line;
1320 class CCredentialsByHost : ICredentialsByHost
1322 public CCredentialsByHost (string userName, string password) {
1323 this.userName = userName;
1324 this.password = password;
1327 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1328 return new NetworkCredential (userName, password);
1331 private string userName;
1332 private string password;