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 #if MONO_SECURITY_ALIAS
33 extern alias MonoSecurity;
36 extern alias PrebuiltSystem;
39 #if MONO_SECURITY_ALIAS
40 using MSI = MonoSecurity::Mono.Security.Interface;
42 using MSI = Mono.Security.Interface;
45 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
47 using X509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
49 using System.Security.Cryptography.X509Certificates;
53 using System.Collections.Generic;
54 using System.ComponentModel;
55 using System.Globalization;
58 using System.Net.Mime;
59 using System.Net.Sockets;
61 using System.Threading;
62 using System.Net.Configuration;
63 using System.Configuration;
64 using System.Net.Security;
65 using System.Security.Authentication;
66 using System.Threading.Tasks;
67 using Mono.Net.Security;
69 namespace System.Net.Mail {
70 [Obsolete ("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
71 public class SmtpClient
79 ICredentialsByHost credentials;
80 string pickupDirectoryLocation;
81 SmtpDeliveryMethod deliveryMethod;
84 X509CertificateCollection clientCertificates;
92 MailAddress defaultFrom;
94 MailMessage messageInProcess;
96 BackgroundWorker worker;
97 object user_async_state;
106 class CancellationException : Exception
111 Mutex mutex = new Mutex ();
122 public SmtpClient (string host)
127 public SmtpClient (string host, int port) {
128 #if CONFIGURATION_DEP
129 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
132 this.host = cfg.Network.Host;
133 this.port = cfg.Network.Port;
134 this.enableSsl = cfg.Network.EnableSsl;
135 TargetName = cfg.Network.TargetName;
136 if (this.TargetName == null)
137 TargetName = "SMTPSVC/" + (host != null ? host : "");
140 if (cfg.Network.UserName != null) {
141 string password = String.Empty;
143 if (cfg.Network.Password != null)
144 password = cfg.Network.Password;
146 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
149 if (!String.IsNullOrEmpty (cfg.From))
150 defaultFrom = new MailAddress (cfg.From);
153 // Just to eliminate the warning, this codepath does not end up in production.
157 if (!String.IsNullOrEmpty (host))
162 else if (this.port == 0)
166 #endregion // Constructors
171 [MonoTODO("Client certificates not used")]
172 public X509CertificateCollection ClientCertificates {
174 if (clientCertificates == null)
175 clientCertificates = new X509CertificateCollection ();
176 return clientCertificates;
182 string TargetName { get; set; }
184 public ICredentialsByHost Credentials {
185 get { return credentials; }
192 public SmtpDeliveryMethod DeliveryMethod {
193 get { return deliveryMethod; }
196 deliveryMethod = value;
200 public bool EnableSsl {
201 get { return enableSsl; }
212 throw new ArgumentNullException ("value");
213 if (value.Length == 0)
214 throw new ArgumentException ("An empty string is not allowed.", "value");
220 public string PickupDirectoryLocation {
221 get { return pickupDirectoryLocation; }
222 set { pickupDirectoryLocation = value; }
229 throw new ArgumentOutOfRangeException ("value");
236 public ServicePoint ServicePoint {
237 get { throw new NotImplementedException (); }
241 get { return timeout; }
244 throw new ArgumentOutOfRangeException ("value");
250 public bool UseDefaultCredentials {
251 get { return false; }
252 [MonoNotSupported ("no DefaultCredential support in Mono")]
255 throw new NotImplementedException ("Default credentials are not supported");
260 #endregion // Properties
264 public event SendCompletedEventHandler SendCompleted;
269 public void Dispose ()
274 [MonoTODO ("Does nothing at the moment.")]
275 protected virtual void Dispose (bool disposing)
277 // 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 string dt = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
555 // remove ':' from time zone offset (e.g. from "+01:00")
556 dt = dt.Remove(dt.Length - 3, 1);
557 SendHeader(HeaderName.Date, dt);
559 SendHeader (HeaderName.From, EncodeAddress(from));
560 SendHeader (HeaderName.To, EncodeAddresses(message.To));
561 if (message.CC.Count > 0)
562 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
563 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
565 foreach (string s in message.Headers.AllKeys)
566 SendHeader (s, message.Headers [s]);
568 AddPriorityHeader (message);
571 if (message.Attachments.Count > 0)
572 SendWithAttachments (message);
574 SendWithoutAttachments (message, null, false);
578 if (writer != null) writer.Close(); writer = null;
582 private void SendCore (MailMessage message)
587 if (IsError (status))
588 throw new SmtpException (status.StatusCode, status.Description);
592 // FIXME: parse the list of extensions so we don't bother wasting
593 // our time trying commands if they aren't supported.
595 // Get the FQDN of the local machine
596 string fqdn = Dns.GetHostEntry (Dns.GetHostName ()).HostName;
597 status = SendCommand ("EHLO " + fqdn);
599 if (IsError (status)) {
600 status = SendCommand ("HELO " + fqdn);
602 if (IsError (status))
603 throw new SmtpException (status.StatusCode, status.Description);
605 // Parse ESMTP extensions
606 string extens = status.Description;
609 ParseExtensions (extens);
613 InitiateSecureConnection ();
615 writer = new StreamWriter (stream);
616 reader = new StreamReader (stream);
617 status = SendCommand ("EHLO " + fqdn);
619 if (IsError (status)) {
620 status = SendCommand ("HELO " + fqdn);
622 if (IsError (status))
623 throw new SmtpException (status.StatusCode, status.Description);
625 // Parse ESMTP extensions
626 string extens = status.Description;
628 ParseExtensions (extens);
632 if (authMechs != AuthMechs.None)
635 // The envelope sender: use 'Sender:' in preference of 'From:'
636 MailAddress sender = message.Sender;
638 sender = message.From;
640 sender = defaultFrom;
643 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
644 if (IsError (status)) {
645 throw new SmtpException (status.StatusCode, status.Description);
648 // Send RCPT TO: for all recipients
649 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
651 for (int i = 0; i < message.To.Count; i ++) {
652 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
653 if (IsError (status))
654 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
656 for (int i = 0; i < message.CC.Count; i ++) {
657 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
658 if (IsError (status))
659 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
661 for (int i = 0; i < message.Bcc.Count; i ++) {
662 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
663 if (IsError (status))
664 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
668 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
671 status = SendCommand ("DATA");
672 if (IsError (status))
673 throw new SmtpException (status.StatusCode, status.Description);
675 // Send message headers
676 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
677 // remove ':' from time zone offset (e.g. from "+01:00")
678 dt = dt.Remove (dt.Length - 3, 1);
679 SendHeader (HeaderName.Date, dt);
681 MailAddress from = message.From;
685 SendHeader (HeaderName.From, EncodeAddress (from));
686 SendHeader (HeaderName.To, EncodeAddresses (message.To));
687 if (message.CC.Count > 0)
688 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
689 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
693 switch (message.Priority){
694 case MailPriority.Normal:
698 case MailPriority.Low:
702 case MailPriority.High:
706 SendHeader ("Priority", v);
707 if (message.Sender != null)
708 SendHeader ("Sender", EncodeAddress (message.Sender));
709 if (message.ReplyToList.Count > 0)
710 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
712 foreach (string s in message.Headers.AllKeys)
713 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
715 AddPriorityHeader (message);
718 if (message.Attachments.Count > 0)
719 SendWithAttachments (message);
721 SendWithoutAttachments (message, null, false);
726 if (IsError (status))
727 throw new SmtpException (status.StatusCode, status.Description);
730 status = SendCommand ("QUIT");
731 } catch (System.IO.IOException) {
732 // We excuse server for the rude connection closing as a response to QUIT
736 public void Send (string from, string to, string subject, string body)
738 Send (new MailMessage (from, to, subject, body));
741 public Task SendMailAsync (MailMessage message)
743 var tcs = new TaskCompletionSource<object> ();
744 SendCompletedEventHandler handler = null;
745 handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
746 SendCompleted += handler;
747 SendAsync (message, tcs);
751 public Task SendMailAsync (string from, string recipients, string subject, string body)
753 return SendMailAsync (new MailMessage (from, recipients, subject, body));
756 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
758 if (source != e.UserState)
761 client.SendCompleted -= handler;
763 if (e.Error != null) {
764 source.SetException (e.Error);
769 source.SetCanceled ();
773 source.SetResult (null);
776 private void SendDot()
778 writer.Write(".\r\n");
782 private void SendData (string data)
784 if (String.IsNullOrEmpty (data)) {
785 writer.Write("\r\n");
790 StringReader sr = new StringReader (data);
792 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
793 while ((line = sr.ReadLine ()) != null) {
794 CheckCancellation ();
798 for (i = 0; i < line.Length; i++) {
802 if (i > 0 && i == line.Length) {
807 writer.Write ("\r\n");
812 public void SendAsync (MailMessage message, object userToken)
815 throw new InvalidOperationException ("Another SendAsync operation is in progress");
817 worker = new BackgroundWorker ();
818 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
820 user_async_state = ea.Argument;
822 } catch (Exception ex) {
827 worker.WorkerSupportsCancellation = true;
828 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
829 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
830 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
832 worker.RunWorkerAsync (userToken);
835 public void SendAsync (string from, string to, string subject, string body, object userToken)
837 SendAsync (new MailMessage (from, to, subject, body), userToken);
840 public void SendAsyncCancel ()
843 throw new InvalidOperationException ("SendAsync operation is not in progress");
844 worker.CancelAsync ();
847 private void AddPriorityHeader (MailMessage message) {
848 switch (message.Priority) {
849 case MailPriority.High:
850 SendHeader (HeaderName.Priority, "Urgent");
851 SendHeader (HeaderName.Importance, "high");
852 SendHeader (HeaderName.XPriority, "1");
854 case MailPriority.Low:
855 SendHeader (HeaderName.Priority, "Non-Urgent");
856 SendHeader (HeaderName.Importance, "low");
857 SendHeader (HeaderName.XPriority, "5");
862 private void SendSimpleBody (MailMessage message) {
863 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
864 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
865 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
866 SendData (string.Empty);
868 SendData (EncodeBody (message));
871 private void SendBodylessSingleAlternate (AlternateView av) {
872 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
873 if (av.TransferEncoding != TransferEncoding.SevenBit)
874 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
875 SendData (string.Empty);
877 SendData (EncodeBody (av));
880 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
882 if (message.Body == null && message.AlternateViews.Count == 1)
883 SendBodylessSingleAlternate (message.AlternateViews [0]);
884 else if (message.AlternateViews.Count > 0)
885 SendBodyWithAlternateViews (message, boundary, attachmentExists);
887 SendSimpleBody (message);
891 private void SendWithAttachments (MailMessage message) {
892 string boundary = GenerateBoundary ();
894 // first "multipart/mixed"
895 ContentType messageContentType = new ContentType ();
896 messageContentType.Boundary = boundary;
897 messageContentType.MediaType = "multipart/mixed";
898 messageContentType.CharSet = null;
900 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
901 SendData (String.Empty);
904 Attachment body = null;
906 if (message.AlternateViews.Count > 0)
907 SendWithoutAttachments (message, boundary, true);
909 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
910 message.Attachments.Insert (0, body);
914 SendAttachments (message, body, boundary);
917 message.Attachments.Remove (body);
920 EndSection (boundary);
923 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
925 AlternateViewCollection alternateViews = message.AlternateViews;
927 string inner_boundary = GenerateBoundary ();
929 ContentType messageContentType = new ContentType ();
930 messageContentType.Boundary = inner_boundary;
931 messageContentType.MediaType = "multipart/alternative";
933 if (!attachmentExists) {
934 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
935 SendData (String.Empty);
939 AlternateView body = null;
940 if (message.Body != null) {
941 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
942 alternateViews.Insert (0, body);
943 StartSection (boundary, messageContentType);
947 // alternate view sections
948 foreach (AlternateView av in alternateViews) {
950 string alt_boundary = null;
951 ContentType contentType;
952 if (av.LinkedResources.Count > 0) {
953 alt_boundary = GenerateBoundary ();
954 contentType = new ContentType ("multipart/related");
955 contentType.Boundary = alt_boundary;
957 contentType.Parameters ["type"] = av.ContentType.ToString ();
958 StartSection (inner_boundary, contentType);
959 StartSection (alt_boundary, av.ContentType, av);
961 contentType = new ContentType (av.ContentType.ToString ());
962 StartSection (inner_boundary, contentType, av);
965 switch (av.TransferEncoding) {
966 case TransferEncoding.Base64:
967 byte [] content = new byte [av.ContentStream.Length];
968 av.ContentStream.Read (content, 0, content.Length);
969 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
971 case TransferEncoding.QuotedPrintable:
972 byte [] bytes = new byte [av.ContentStream.Length];
973 av.ContentStream.Read (bytes, 0, bytes.Length);
974 SendData (ToQuotedPrintable (bytes));
976 case TransferEncoding.SevenBit:
977 case TransferEncoding.Unknown:
978 content = new byte [av.ContentStream.Length];
979 av.ContentStream.Read (content, 0, content.Length);
980 SendData (Encoding.ASCII.GetString (content));
984 if (av.LinkedResources.Count > 0) {
985 SendLinkedResources (message, av.LinkedResources, alt_boundary);
986 EndSection (alt_boundary);
989 if (!attachmentExists)
990 SendData (string.Empty);
995 alternateViews.Remove (body);
997 EndSection (inner_boundary);
1000 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
1002 foreach (LinkedResource lr in resources) {
1003 StartSection (boundary, lr.ContentType, lr);
1005 switch (lr.TransferEncoding) {
1006 case TransferEncoding.Base64:
1007 byte [] content = new byte [lr.ContentStream.Length];
1008 lr.ContentStream.Read (content, 0, content.Length);
1009 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1011 case TransferEncoding.QuotedPrintable:
1012 byte [] bytes = new byte [lr.ContentStream.Length];
1013 lr.ContentStream.Read (bytes, 0, bytes.Length);
1014 SendData (ToQuotedPrintable (bytes));
1016 case TransferEncoding.SevenBit:
1017 case TransferEncoding.Unknown:
1018 content = new byte [lr.ContentStream.Length];
1019 lr.ContentStream.Read (content, 0, content.Length);
1020 SendData (Encoding.ASCII.GetString (content));
1026 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1027 foreach (Attachment att in message.Attachments) {
1028 ContentType contentType = new ContentType (att.ContentType.ToString ());
1029 if (att.Name != null) {
1030 contentType.Name = att.Name;
1031 if (att.NameEncoding != null)
1032 contentType.CharSet = att.NameEncoding.HeaderName;
1033 att.ContentDisposition.FileName = att.Name;
1035 StartSection (boundary, contentType, att, att != body);
1037 byte [] content = new byte [att.ContentStream.Length];
1038 att.ContentStream.Read (content, 0, content.Length);
1039 switch (att.TransferEncoding) {
1040 case TransferEncoding.Base64:
1041 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1043 case TransferEncoding.QuotedPrintable:
1044 SendData (ToQuotedPrintable (content));
1046 case TransferEncoding.SevenBit:
1047 case TransferEncoding.Unknown:
1048 SendData (Encoding.ASCII.GetString (content));
1052 SendData (string.Empty);
1056 private SmtpResponse SendCommand (string command)
1058 writer.Write (command);
1059 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1060 writer.Write ("\r\n");
1065 private void SendHeader (string name, string value)
1067 SendData (String.Format ("{0}: {1}", name, value));
1070 private void StartSection (string section, ContentType sectionContentType)
1072 SendData (String.Format ("--{0}", section));
1073 SendHeader ("content-type", sectionContentType.ToString ());
1074 SendData (string.Empty);
1077 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1079 SendData (String.Format ("--{0}", section));
1080 SendHeader ("content-type", sectionContentType.ToString ());
1081 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1082 if (!string.IsNullOrEmpty (att.ContentId))
1083 SendHeader("content-ID", "<" + att.ContentId + ">");
1084 SendData (string.Empty);
1087 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1088 SendData (String.Format ("--{0}", section));
1089 if (!string.IsNullOrEmpty (att.ContentId))
1090 SendHeader("content-ID", "<" + att.ContentId + ">");
1091 SendHeader ("content-type", sectionContentType.ToString ());
1092 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1093 if (sendDisposition)
1094 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1095 SendData (string.Empty);
1098 // use proper encoding to escape input
1099 private string ToQuotedPrintable (string input, Encoding enc)
1101 byte [] bytes = enc.GetBytes (input);
1102 return ToQuotedPrintable (bytes);
1105 private string ToQuotedPrintable (byte [] bytes)
1107 StringWriter writer = new StringWriter ();
1108 int charsInLine = 0;
1110 StringBuilder sb = new StringBuilder("=", 3);
1111 byte equalSign = (byte)'=';
1114 foreach (byte i in bytes) {
1115 if (i > 127 || i == equalSign) {
1117 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1120 c = Convert.ToChar (i);
1121 if (c == '\r' || c == '\n') {
1129 charsInLine += curLen;
1130 if (charsInLine > 75) {
1131 writer.Write ("=\r\n");
1132 charsInLine = curLen;
1137 writer.Write (sb.ToString ());
1140 return writer.ToString ();
1142 private static string GetTransferEncodingName (TransferEncoding encoding)
1145 case TransferEncoding.QuotedPrintable:
1146 return "quoted-printable";
1147 case TransferEncoding.SevenBit:
1149 case TransferEncoding.Base64:
1155 private void InitiateSecureConnection () {
1156 SmtpResponse response = SendCommand ("STARTTLS");
1158 if (IsError (response)) {
1159 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1163 var tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
1164 var settings = MSI.MonoTlsSettings.CopyDefaultSettings ();
1165 settings.UseServicePointManagerCallback = true;
1166 var sslStream = tlsProvider.CreateSslStream (stream, false, settings);
1167 CheckCancellation ();
1168 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1169 stream = sslStream.AuthenticatedStream;
1172 throw new SystemException ("You are using an incomplete System.dll build");
1176 void Authenticate ()
1178 string user = null, pass = null;
1180 if (UseDefaultCredentials) {
1181 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1182 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1183 } else if (Credentials != null) {
1184 user = Credentials.GetCredential (host, port, "smtp").UserName;
1185 pass = Credentials.GetCredential (host, port, "smtp").Password;
1190 Authenticate (user, pass);
1193 void CheckStatus (SmtpResponse status, int i)
1195 if (((int) status.StatusCode) != i)
1196 throw new SmtpException (status.StatusCode, status.Description);
1199 void ThrowIfError (SmtpResponse status)
1201 if (IsError (status))
1202 throw new SmtpException (status.StatusCode, status.Description);
1205 void Authenticate (string user, string password)
1207 if (authMechs == AuthMechs.None)
1210 SmtpResponse status;
1212 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1213 status = SendCommand ("AUTH DIGEST-MD5");
1214 CheckStatus (status, 334);
1215 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1216 Console.WriteLine ("CHALLENGE: {0}", challenge);
1217 DigestSession session = new DigestSession ();
1218 session.Parse (false, challenge);
1219 string response = session.Authenticate (this, user, password);
1220 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1221 CheckStatus (status, 235);
1223 if ((authMechs & AuthMechs.Login) != 0) {
1224 status = SendCommand ("AUTH LOGIN");
1225 CheckStatus (status, 334);
1226 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1227 CheckStatus (status, 334);
1228 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1229 CheckStatus (status, 235);
1230 } else if ((authMechs & AuthMechs.Plain) != 0) {
1231 string s = String.Format ("\0{0}\0{1}", user, password);
1232 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1233 status = SendCommand ("AUTH PLAIN " + s);
1234 CheckStatus (status, 235);
1236 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1240 #endregion // Methods
1242 // The HeaderName struct is used to store constant string values representing mail headers.
1243 private struct HeaderName {
1244 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1245 public const string ContentType = "Content-Type";
1246 public const string Bcc = "Bcc";
1247 public const string Cc = "Cc";
1248 public const string From = "From";
1249 public const string Subject = "Subject";
1250 public const string To = "To";
1251 public const string MimeVersion = "MIME-Version";
1252 public const string MessageId = "Message-ID";
1253 public const string Priority = "Priority";
1254 public const string Importance = "Importance";
1255 public const string XPriority = "X-Priority";
1256 public const string Date = "Date";
1259 // This object encapsulates the status code and description of an SMTP response.
1260 private struct SmtpResponse {
1261 public SmtpStatusCode StatusCode;
1262 public string Description;
1264 public static SmtpResponse Parse (string line) {
1265 SmtpResponse response = new SmtpResponse ();
1267 if (line.Length < 4)
1268 throw new SmtpException ("Response is to short " +
1271 if ((line [3] != ' ') && (line [3] != '-'))
1272 throw new SmtpException ("Response format is wrong.(" +
1275 // parse the response code
1276 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1278 // set the raw response
1279 response.Description = line;
1286 class CCredentialsByHost : ICredentialsByHost
1288 public CCredentialsByHost (string userName, string password) {
1289 this.userName = userName;
1290 this.password = password;
1293 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1294 return new NetworkCredential (userName, password);
1297 private string userName;
1298 private string password;