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;
58 using System.Threading.Tasks;
60 namespace System.Net.Mail {
61 public class SmtpClient
69 ICredentialsByHost credentials;
70 string pickupDirectoryLocation;
71 SmtpDeliveryMethod deliveryMethod;
74 X509CertificateCollection clientCertificates;
82 MailAddress defaultFrom;
84 MailMessage messageInProcess;
86 BackgroundWorker worker;
87 object user_async_state;
96 class CancellationException : Exception
101 Mutex mutex = new Mutex ();
112 public SmtpClient (string host)
117 public SmtpClient (string host, int port) {
118 #if CONFIGURATION_DEP
119 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
122 this.host = cfg.Network.Host;
123 this.port = cfg.Network.Port;
124 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))
152 else if (this.port == 0)
156 #endregion // Constructors
161 [MonoTODO("Client certificates not used")]
162 public X509CertificateCollection ClientCertificates {
164 if (clientCertificates == null)
165 clientCertificates = new X509CertificateCollection ();
166 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;
259 public void Dispose ()
264 [MonoTODO ("Does nothing at the moment.")]
265 protected virtual void Dispose (bool disposing)
267 // TODO: We should close all the connections and abort any async operations here
269 private void CheckState ()
271 if (messageInProcess != null)
272 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
275 private static string EncodeAddress(MailAddress address)
277 if (!String.IsNullOrEmpty (address.DisplayName)) {
278 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
279 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
281 return address.ToString ();
284 private static string EncodeAddresses(MailAddressCollection addresses)
286 StringBuilder sb = new StringBuilder();
288 foreach (MailAddress address in addresses) {
292 sb.Append(EncodeAddress(address));
295 return sb.ToString();
298 private string EncodeSubjectRFC2047 (MailMessage message)
300 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
303 private string EncodeBody (MailMessage message)
305 string body = message.Body;
306 Encoding encoding = message.BodyEncoding;
308 switch (message.ContentTransferEncoding) {
309 case TransferEncoding.SevenBit:
311 case TransferEncoding.Base64:
312 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
314 return ToQuotedPrintable (body, encoding);
318 private string EncodeBody (AlternateView av)
320 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
322 byte [] bytes = new byte [av.ContentStream.Length];
323 av.ContentStream.Read (bytes, 0, bytes.Length);
326 switch (av.TransferEncoding) {
327 case TransferEncoding.SevenBit:
328 return Encoding.ASCII.GetString (bytes);
329 case TransferEncoding.Base64:
330 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
332 return ToQuotedPrintable (bytes);
337 private void EndSection (string section)
339 SendData (String.Format ("--{0}--", section));
340 SendData (string.Empty);
343 private string GenerateBoundary ()
345 string output = GenerateBoundary (boundaryIndex);
350 private static string GenerateBoundary (int index)
352 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
355 private bool IsError (SmtpResponse status)
357 return ((int) status.StatusCode) >= 400;
360 protected void OnSendCompleted (AsyncCompletedEventArgs e)
363 if (SendCompleted != null)
364 SendCompleted (this, e);
367 user_async_state = null;
371 private void CheckCancellation ()
373 if (worker != null && worker.CancellationPending)
374 throw new CancellationException ();
377 private SmtpResponse Read () {
378 byte [] buffer = new byte [512];
380 bool lastLine = false;
383 CheckCancellation ();
385 int readLength = stream.Read (buffer, position, buffer.Length - position);
386 if (readLength > 0) {
387 int available = position + readLength - 1;
388 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
389 for (int index = available - 3; ; index--) {
390 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
391 lastLine = buffer [index + 4] == ' ';
397 position += readLength;
399 // check if buffer is full
400 if (position == buffer.Length) {
401 byte [] newBuffer = new byte [buffer.Length * 2];
402 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
412 Encoding encoding = new ASCIIEncoding ();
414 string line = encoding.GetString (buffer, 0, position - 1);
416 // parse the line to the lastResponse object
417 SmtpResponse response = SmtpResponse.Parse (line);
421 throw new System.IO.IOException ("Connection closed");
425 void ResetExtensions()
427 authMechs = AuthMechs.None;
430 void ParseExtensions (string extens)
432 string[] parts = extens.Split ('\n');
434 foreach (string part in parts) {
438 string start = part.Substring (4);
439 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
440 string[] options = start.Split (' ');
441 for (int k = 1; k < options.Length; k++) {
442 string option = options[k].Trim();
443 // GSSAPI, KERBEROS_V4, NTLM not supported
447 authMechs |= AuthMechs.CramMD5;
450 authMechs |= AuthMechs.DigestMD5;
454 authMechs |= AuthMechs.Login;
457 authMechs |= AuthMechs.Plain;
465 public void Send (MailMessage message)
468 throw new ArgumentNullException ("message");
470 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
471 throw new InvalidOperationException ("The SMTP host was not specified");
472 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
473 throw new NotSupportedException("IIS delivery is not supported");
478 // Block while sending
481 messageInProcess = message;
482 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
483 SendToFile (message);
485 SendInternal (message);
486 } catch (CancellationException) {
487 // This exception is introduced for convenient cancellation process.
488 } catch (SmtpException) {
490 } catch (Exception ex) {
491 throw new SmtpException ("Message could not be sent.", ex);
493 // Release the mutex to allow other threads access
494 mutex.ReleaseMutex ();
495 messageInProcess = null;
499 private void SendInternal (MailMessage message)
501 CheckCancellation ();
504 client = new TcpClient (host, port);
505 stream = client.GetStream ();
506 // FIXME: this StreamWriter creation is bogus.
507 // It expects as if a Stream were able to switch to SSL
508 // mode (such behavior is only in Mainsoft Socket API).
509 writer = new StreamWriter (stream);
510 reader = new StreamReader (stream);
525 // FIXME: simple implementation, could be brushed up.
526 private void SendToFile (MailMessage message)
528 if (!Path.IsPathRooted (pickupDirectoryLocation))
529 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
531 string filename = Path.Combine (pickupDirectoryLocation,
532 Guid.NewGuid() + ".eml");
535 writer = new StreamWriter(filename);
537 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
538 // For all we know, defaultFrom may be the envelope sender
539 // For now, we are no worse than some versions of .NET
540 MailAddress from = message.From;
544 string dt = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
545 // remove ':' from time zone offset (e.g. from "+01:00")
546 dt = dt.Remove(dt.Length - 3, 1);
547 SendHeader(HeaderName.Date, dt);
549 SendHeader (HeaderName.From, EncodeAddress(from));
550 SendHeader (HeaderName.To, EncodeAddresses(message.To));
551 if (message.CC.Count > 0)
552 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
553 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
555 foreach (string s in message.Headers.AllKeys)
556 SendHeader (s, message.Headers [s]);
558 AddPriorityHeader (message);
561 if (message.Attachments.Count > 0)
562 SendWithAttachments (message);
564 SendWithoutAttachments (message, null, false);
568 if (writer != null) writer.Close(); writer = null;
572 private void SendCore (MailMessage message)
577 if (IsError (status))
578 throw new SmtpException (status.StatusCode, status.Description);
582 // FIXME: parse the list of extensions so we don't bother wasting
583 // our time trying commands if they aren't supported.
584 status = SendCommand ("EHLO " + Dns.GetHostName ());
586 if (IsError (status)) {
587 status = SendCommand ("HELO " + Dns.GetHostName ());
589 if (IsError (status))
590 throw new SmtpException (status.StatusCode, status.Description);
592 // Parse ESMTP extensions
593 string extens = status.Description;
596 ParseExtensions (extens);
600 InitiateSecureConnection ();
602 writer = new StreamWriter (stream);
603 reader = new StreamReader (stream);
604 status = SendCommand ("EHLO " + Dns.GetHostName ());
606 if (IsError (status)) {
607 status = SendCommand ("HELO " + Dns.GetHostName ());
609 if (IsError (status))
610 throw new SmtpException (status.StatusCode, status.Description);
612 // Parse ESMTP extensions
613 string extens = status.Description;
615 ParseExtensions (extens);
619 if (authMechs != AuthMechs.None)
622 // The envelope sender: use 'Sender:' in preference of 'From:'
623 MailAddress sender = message.Sender;
625 sender = message.From;
627 sender = defaultFrom;
630 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
631 if (IsError (status)) {
632 throw new SmtpException (status.StatusCode, status.Description);
635 // Send RCPT TO: for all recipients
636 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
638 for (int i = 0; i < message.To.Count; i ++) {
639 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
640 if (IsError (status))
641 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
643 for (int i = 0; i < message.CC.Count; i ++) {
644 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
645 if (IsError (status))
646 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
648 for (int i = 0; i < message.Bcc.Count; i ++) {
649 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
650 if (IsError (status))
651 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
655 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
658 status = SendCommand ("DATA");
659 if (IsError (status))
660 throw new SmtpException (status.StatusCode, status.Description);
662 // Send message headers
663 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
664 // remove ':' from time zone offset (e.g. from "+01:00")
665 dt = dt.Remove (dt.Length - 3, 1);
666 SendHeader (HeaderName.Date, dt);
668 MailAddress from = message.From;
672 SendHeader (HeaderName.From, EncodeAddress (from));
673 SendHeader (HeaderName.To, EncodeAddresses (message.To));
674 if (message.CC.Count > 0)
675 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
676 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
680 switch (message.Priority){
681 case MailPriority.Normal:
685 case MailPriority.Low:
689 case MailPriority.High:
693 SendHeader ("Priority", v);
694 if (message.Sender != null)
695 SendHeader ("Sender", EncodeAddress (message.Sender));
696 if (message.ReplyToList.Count > 0)
697 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
699 foreach (string s in message.Headers.AllKeys)
700 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
702 AddPriorityHeader (message);
705 if (message.Attachments.Count > 0)
706 SendWithAttachments (message);
708 SendWithoutAttachments (message, null, false);
713 if (IsError (status))
714 throw new SmtpException (status.StatusCode, status.Description);
717 status = SendCommand ("QUIT");
718 } catch (System.IO.IOException) {
719 // We excuse server for the rude connection closing as a response to QUIT
723 public void Send (string from, string to, string subject, string body)
725 Send (new MailMessage (from, to, subject, body));
728 public Task SendMailAsync (MailMessage message)
730 var tcs = new TaskCompletionSource<object> ();
731 SendCompletedEventHandler handler = null;
732 handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
733 SendCompleted += handler;
734 SendAsync (message, tcs);
738 public Task SendMailAsync (string from, string recipients, string subject, string body)
740 return SendMailAsync (new MailMessage (from, recipients, subject, body));
743 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
745 if (source != e.UserState)
748 client.SendCompleted -= handler;
750 if (e.Error != null) {
751 source.SetException (e.Error);
756 source.SetCanceled ();
760 source.SetResult (null);
763 private void SendDot()
765 writer.Write(".\r\n");
769 private void SendData (string data)
771 if (String.IsNullOrEmpty (data)) {
772 writer.Write("\r\n");
777 StringReader sr = new StringReader (data);
779 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
780 while ((line = sr.ReadLine ()) != null) {
781 CheckCancellation ();
785 for (i = 0; i < line.Length; i++) {
789 if (i > 0 && i == line.Length) {
794 writer.Write ("\r\n");
799 public void SendAsync (MailMessage message, object userToken)
802 throw new InvalidOperationException ("Another SendAsync operation is in progress");
804 worker = new BackgroundWorker ();
805 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
807 user_async_state = ea.Argument;
809 } catch (Exception ex) {
814 worker.WorkerSupportsCancellation = true;
815 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
816 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
817 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
819 worker.RunWorkerAsync (userToken);
822 public void SendAsync (string from, string to, string subject, string body, object userToken)
824 SendAsync (new MailMessage (from, to, subject, body), userToken);
827 public void SendAsyncCancel ()
830 throw new InvalidOperationException ("SendAsync operation is not in progress");
831 worker.CancelAsync ();
834 private void AddPriorityHeader (MailMessage message) {
835 switch (message.Priority) {
836 case MailPriority.High:
837 SendHeader (HeaderName.Priority, "Urgent");
838 SendHeader (HeaderName.Importance, "high");
839 SendHeader (HeaderName.XPriority, "1");
841 case MailPriority.Low:
842 SendHeader (HeaderName.Priority, "Non-Urgent");
843 SendHeader (HeaderName.Importance, "low");
844 SendHeader (HeaderName.XPriority, "5");
849 private void SendSimpleBody (MailMessage message) {
850 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
851 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
852 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
853 SendData (string.Empty);
855 SendData (EncodeBody (message));
858 private void SendBodylessSingleAlternate (AlternateView av) {
859 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
860 if (av.TransferEncoding != TransferEncoding.SevenBit)
861 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
862 SendData (string.Empty);
864 SendData (EncodeBody (av));
867 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
869 if (message.Body == null && message.AlternateViews.Count == 1)
870 SendBodylessSingleAlternate (message.AlternateViews [0]);
871 else if (message.AlternateViews.Count > 0)
872 SendBodyWithAlternateViews (message, boundary, attachmentExists);
874 SendSimpleBody (message);
878 private void SendWithAttachments (MailMessage message) {
879 string boundary = GenerateBoundary ();
881 // first "multipart/mixed"
882 ContentType messageContentType = new ContentType ();
883 messageContentType.Boundary = boundary;
884 messageContentType.MediaType = "multipart/mixed";
885 messageContentType.CharSet = null;
887 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
888 SendData (String.Empty);
891 Attachment body = null;
893 if (message.AlternateViews.Count > 0)
894 SendWithoutAttachments (message, boundary, true);
896 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
897 message.Attachments.Insert (0, body);
901 SendAttachments (message, body, boundary);
904 message.Attachments.Remove (body);
907 EndSection (boundary);
910 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
912 AlternateViewCollection alternateViews = message.AlternateViews;
914 string inner_boundary = GenerateBoundary ();
916 ContentType messageContentType = new ContentType ();
917 messageContentType.Boundary = inner_boundary;
918 messageContentType.MediaType = "multipart/alternative";
920 if (!attachmentExists) {
921 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
922 SendData (String.Empty);
926 AlternateView body = null;
927 if (message.Body != null) {
928 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
929 alternateViews.Insert (0, body);
930 StartSection (boundary, messageContentType);
934 // alternate view sections
935 foreach (AlternateView av in alternateViews) {
937 string alt_boundary = null;
938 ContentType contentType;
939 if (av.LinkedResources.Count > 0) {
940 alt_boundary = GenerateBoundary ();
941 contentType = new ContentType ("multipart/related");
942 contentType.Boundary = alt_boundary;
944 contentType.Parameters ["type"] = av.ContentType.ToString ();
945 StartSection (inner_boundary, contentType);
946 StartSection (alt_boundary, av.ContentType, av);
948 contentType = new ContentType (av.ContentType.ToString ());
949 StartSection (inner_boundary, contentType, av);
952 switch (av.TransferEncoding) {
953 case TransferEncoding.Base64:
954 byte [] content = new byte [av.ContentStream.Length];
955 av.ContentStream.Read (content, 0, content.Length);
956 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
958 case TransferEncoding.QuotedPrintable:
959 byte [] bytes = new byte [av.ContentStream.Length];
960 av.ContentStream.Read (bytes, 0, bytes.Length);
961 SendData (ToQuotedPrintable (bytes));
963 case TransferEncoding.SevenBit:
964 case TransferEncoding.Unknown:
965 content = new byte [av.ContentStream.Length];
966 av.ContentStream.Read (content, 0, content.Length);
967 SendData (Encoding.ASCII.GetString (content));
971 if (av.LinkedResources.Count > 0) {
972 SendLinkedResources (message, av.LinkedResources, alt_boundary);
973 EndSection (alt_boundary);
976 if (!attachmentExists)
977 SendData (string.Empty);
982 alternateViews.Remove (body);
984 EndSection (inner_boundary);
987 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
989 foreach (LinkedResource lr in resources) {
990 StartSection (boundary, lr.ContentType, lr);
992 switch (lr.TransferEncoding) {
993 case TransferEncoding.Base64:
994 byte [] content = new byte [lr.ContentStream.Length];
995 lr.ContentStream.Read (content, 0, content.Length);
996 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
998 case TransferEncoding.QuotedPrintable:
999 byte [] bytes = new byte [lr.ContentStream.Length];
1000 lr.ContentStream.Read (bytes, 0, bytes.Length);
1001 SendData (ToQuotedPrintable (bytes));
1003 case TransferEncoding.SevenBit:
1004 case TransferEncoding.Unknown:
1005 content = new byte [lr.ContentStream.Length];
1006 lr.ContentStream.Read (content, 0, content.Length);
1007 SendData (Encoding.ASCII.GetString (content));
1013 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1014 foreach (Attachment att in message.Attachments) {
1015 ContentType contentType = new ContentType (att.ContentType.ToString ());
1016 if (att.Name != null) {
1017 contentType.Name = att.Name;
1018 if (att.NameEncoding != null)
1019 contentType.CharSet = att.NameEncoding.HeaderName;
1020 att.ContentDisposition.FileName = att.Name;
1022 StartSection (boundary, contentType, att, att != body);
1024 byte [] content = new byte [att.ContentStream.Length];
1025 att.ContentStream.Read (content, 0, content.Length);
1026 switch (att.TransferEncoding) {
1027 case TransferEncoding.Base64:
1028 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1030 case TransferEncoding.QuotedPrintable:
1031 SendData (ToQuotedPrintable (content));
1033 case TransferEncoding.SevenBit:
1034 case TransferEncoding.Unknown:
1035 SendData (Encoding.ASCII.GetString (content));
1039 SendData (string.Empty);
1043 private SmtpResponse SendCommand (string command)
1045 writer.Write (command);
1046 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1047 writer.Write ("\r\n");
1052 private void SendHeader (string name, string value)
1054 SendData (String.Format ("{0}: {1}", name, value));
1057 private void StartSection (string section, ContentType sectionContentType)
1059 SendData (String.Format ("--{0}", section));
1060 SendHeader ("content-type", sectionContentType.ToString ());
1061 SendData (string.Empty);
1064 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1066 SendData (String.Format ("--{0}", section));
1067 SendHeader ("content-type", sectionContentType.ToString ());
1068 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1069 if (!string.IsNullOrEmpty (att.ContentId))
1070 SendHeader("content-ID", "<" + att.ContentId + ">");
1071 SendData (string.Empty);
1074 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1075 SendData (String.Format ("--{0}", section));
1076 if (!string.IsNullOrEmpty (att.ContentId))
1077 SendHeader("content-ID", "<" + att.ContentId + ">");
1078 SendHeader ("content-type", sectionContentType.ToString ());
1079 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1080 if (sendDisposition)
1081 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1082 SendData (string.Empty);
1085 // use proper encoding to escape input
1086 private string ToQuotedPrintable (string input, Encoding enc)
1088 byte [] bytes = enc.GetBytes (input);
1089 return ToQuotedPrintable (bytes);
1092 private string ToQuotedPrintable (byte [] bytes)
1094 StringWriter writer = new StringWriter ();
1095 int charsInLine = 0;
1097 StringBuilder sb = new StringBuilder("=", 3);
1098 byte equalSign = (byte)'=';
1101 foreach (byte i in bytes) {
1102 if (i > 127 || i == equalSign) {
1104 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1107 c = Convert.ToChar (i);
1108 if (c == '\r' || c == '\n') {
1116 charsInLine += curLen;
1117 if (charsInLine > 75) {
1118 writer.Write ("=\r\n");
1119 charsInLine = curLen;
1124 writer.Write (sb.ToString ());
1127 return writer.ToString ();
1129 private static string GetTransferEncodingName (TransferEncoding encoding)
1132 case TransferEncoding.QuotedPrintable:
1133 return "quoted-printable";
1134 case TransferEncoding.SevenBit:
1136 case TransferEncoding.Base64:
1143 RemoteCertificateValidationCallback callback = delegate (object sender,
1144 X509Certificate certificate,
1146 SslPolicyErrors sslPolicyErrors) {
1147 // honor any exciting callback defined on ServicePointManager
1148 if (ServicePointManager.ServerCertificateValidationCallback != null)
1149 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1150 // otherwise provide our own
1151 if (sslPolicyErrors != SslPolicyErrors.None)
1152 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1157 private void InitiateSecureConnection () {
1158 SmtpResponse response = SendCommand ("STARTTLS");
1160 if (IsError (response)) {
1161 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1165 SslStream sslStream = new SslStream (stream, false, callback, null);
1166 CheckCancellation ();
1167 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1171 throw new SystemException ("You are using an incomplete System.dll build");
1175 void Authenticate ()
1177 string user = null, pass = null;
1179 if (UseDefaultCredentials) {
1180 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1181 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1182 } else if (Credentials != null) {
1183 user = Credentials.GetCredential (host, port, "smtp").UserName;
1184 pass = Credentials.GetCredential (host, port, "smtp").Password;
1189 Authenticate (user, pass);
1192 void CheckStatus (SmtpResponse status, int i)
1194 if (((int) status.StatusCode) != i)
1195 throw new SmtpException (status.StatusCode, status.Description);
1198 void ThrowIfError (SmtpResponse status)
1200 if (IsError (status))
1201 throw new SmtpException (status.StatusCode, status.Description);
1204 void Authenticate (string user, string password)
1206 if (authMechs == AuthMechs.None)
1209 SmtpResponse status;
1211 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1212 status = SendCommand ("AUTH DIGEST-MD5");
1213 CheckStatus (status, 334);
1214 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1215 Console.WriteLine ("CHALLENGE: {0}", challenge);
1216 DigestSession session = new DigestSession ();
1217 session.Parse (false, challenge);
1218 string response = session.Authenticate (this, user, password);
1219 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1220 CheckStatus (status, 235);
1222 if ((authMechs & AuthMechs.Login) != 0) {
1223 status = SendCommand ("AUTH LOGIN");
1224 CheckStatus (status, 334);
1225 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1226 CheckStatus (status, 334);
1227 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1228 CheckStatus (status, 235);
1229 } else if ((authMechs & AuthMechs.Plain) != 0) {
1230 string s = String.Format ("\0{0}\0{1}", user, password);
1231 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1232 status = SendCommand ("AUTH PLAIN " + s);
1233 CheckStatus (status, 235);
1235 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1239 #endregion // Methods
1241 // The HeaderName struct is used to store constant string values representing mail headers.
1242 private struct HeaderName {
1243 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1244 public const string ContentType = "Content-Type";
1245 public const string Bcc = "Bcc";
1246 public const string Cc = "Cc";
1247 public const string From = "From";
1248 public const string Subject = "Subject";
1249 public const string To = "To";
1250 public const string MimeVersion = "MIME-Version";
1251 public const string MessageId = "Message-ID";
1252 public const string Priority = "Priority";
1253 public const string Importance = "Importance";
1254 public const string XPriority = "X-Priority";
1255 public const string Date = "Date";
1258 // This object encapsulates the status code and description of an SMTP response.
1259 private struct SmtpResponse {
1260 public SmtpStatusCode StatusCode;
1261 public string Description;
1263 public static SmtpResponse Parse (string line) {
1264 SmtpResponse response = new SmtpResponse ();
1266 if (line.Length < 4)
1267 throw new SmtpException ("Response is to short " +
1270 if ((line [3] != ' ') && (line [3] != '-'))
1271 throw new SmtpException ("Response format is wrong.(" +
1274 // parse the response code
1275 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1277 // set the raw response
1278 response.Description = line;
1285 class CCredentialsByHost : ICredentialsByHost
1287 public CCredentialsByHost (string userName, string password) {
1288 this.userName = userName;
1289 this.password = password;
1292 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1293 return new NetworkCredential (userName, password);
1296 private string userName;
1297 private string password;