2 // System.Net.Mail.SmtpClient.cs
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2004
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 extern alias PrebuiltSystem;
36 using System.Collections.Generic;
37 using System.ComponentModel;
38 using System.Globalization;
41 using System.Net.Mime;
42 using System.Net.Sockets;
43 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
46 using System.Reflection;
47 using System.Net.Configuration;
48 using System.Configuration;
49 using System.Net.Security;
50 using System.Security.Authentication;
53 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
56 namespace System.Net.Mail {
57 public class SmtpClient
67 ICredentialsByHost credentials;
68 string pickupDirectoryLocation;
69 SmtpDeliveryMethod deliveryMethod;
72 X509CertificateCollection clientCertificates;
80 MailAddress defaultFrom;
82 MailMessage messageInProcess;
84 BackgroundWorker worker;
85 object user_async_state;
94 class CancellationException : Exception
99 Mutex mutex = new Mutex ();
110 public SmtpClient (string host)
115 public SmtpClient (string host, int port) {
116 #if CONFIGURATION_DEP
117 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
120 this.host = cfg.Network.Host;
121 this.port = cfg.Network.Port;
123 this.enableSsl = cfg.Network.EnableSsl;
125 TargetName = cfg.Network.TargetName;
126 if (this.TargetName == null)
127 TargetName = "SMTPSVC/" + (host != null ? host : "");
130 if (cfg.Network.UserName != null) {
131 string password = String.Empty;
133 if (cfg.Network.Password != null)
134 password = cfg.Network.Password;
136 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
139 if (!String.IsNullOrEmpty (cfg.From))
140 defaultFrom = new MailAddress (cfg.From);
143 // Just to eliminate the warning, this codepath does not end up in production.
147 if (!String.IsNullOrEmpty (host))
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;
174 string TargetName { get; set; }
176 public ICredentialsByHost Credentials {
177 get { return credentials; }
184 public SmtpDeliveryMethod DeliveryMethod {
185 get { return deliveryMethod; }
188 deliveryMethod = value;
192 public bool EnableSsl {
193 get { return enableSsl; }
204 throw new ArgumentNullException ("value");
205 if (value.Length == 0)
206 throw new ArgumentException ("An empty string is not allowed.", "value");
212 public string PickupDirectoryLocation {
213 get { return pickupDirectoryLocation; }
214 set { pickupDirectoryLocation = value; }
221 throw new ArgumentOutOfRangeException ("value");
228 public ServicePoint ServicePoint {
229 get { throw new NotImplementedException (); }
233 get { return timeout; }
236 throw new ArgumentOutOfRangeException ("value");
242 public bool UseDefaultCredentials {
243 get { return false; }
244 [MonoNotSupported ("no DefaultCredential support in Mono")]
247 throw new NotImplementedException ("Default credentials are not supported");
252 #endregion // Properties
256 public event SendCompletedEventHandler SendCompleted;
262 public void Dispose ()
267 [MonoTODO ("Does nothing at the moment.")]
268 protected virtual void Dispose (bool disposing)
270 // TODO: We should close all the connections and abort any async operations here
273 private void CheckState ()
275 if (messageInProcess != null)
276 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
279 private static string EncodeAddress(MailAddress address)
281 if (!String.IsNullOrEmpty (address.DisplayName)) {
282 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
283 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
285 return address.ToString ();
288 private static string EncodeAddresses(MailAddressCollection addresses)
290 StringBuilder sb = new StringBuilder();
292 foreach (MailAddress address in addresses) {
296 sb.Append(EncodeAddress(address));
299 return sb.ToString();
302 private string EncodeSubjectRFC2047 (MailMessage message)
304 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
307 private string EncodeBody (MailMessage message)
309 string body = message.Body;
310 Encoding encoding = message.BodyEncoding;
312 switch (message.ContentTransferEncoding) {
313 case TransferEncoding.SevenBit:
315 case TransferEncoding.Base64:
316 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
318 return ToQuotedPrintable (body, encoding);
322 private string EncodeBody (AlternateView av)
324 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
326 byte [] bytes = new byte [av.ContentStream.Length];
327 av.ContentStream.Read (bytes, 0, bytes.Length);
330 switch (av.TransferEncoding) {
331 case TransferEncoding.SevenBit:
332 return Encoding.ASCII.GetString (bytes);
333 case TransferEncoding.Base64:
334 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
336 return ToQuotedPrintable (bytes);
341 private void EndSection (string section)
343 SendData (String.Format ("--{0}--", section));
344 SendData (string.Empty);
347 private string GenerateBoundary ()
349 string output = GenerateBoundary (boundaryIndex);
354 private static string GenerateBoundary (int index)
356 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
359 private bool IsError (SmtpResponse status)
361 return ((int) status.StatusCode) >= 400;
364 protected void OnSendCompleted (AsyncCompletedEventArgs e)
367 if (SendCompleted != null)
368 SendCompleted (this, e);
371 user_async_state = null;
375 private void CheckCancellation ()
377 if (worker != null && worker.CancellationPending)
378 throw new CancellationException ();
381 private SmtpResponse Read () {
382 byte [] buffer = new byte [512];
384 bool lastLine = false;
387 CheckCancellation ();
389 int readLength = stream.Read (buffer, position, buffer.Length - position);
390 if (readLength > 0) {
391 int available = position + readLength - 1;
392 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
393 for (int index = available - 3; ; index--) {
394 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
395 lastLine = buffer [index + 4] == ' ';
401 position += readLength;
403 // check if buffer is full
404 if (position == buffer.Length) {
405 byte [] newBuffer = new byte [buffer.Length * 2];
406 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
416 Encoding encoding = new ASCIIEncoding ();
418 string line = encoding.GetString (buffer, 0, position - 1);
420 // parse the line to the lastResponse object
421 SmtpResponse response = SmtpResponse.Parse (line);
425 throw new System.IO.IOException ("Connection closed");
429 void ResetExtensions()
431 authMechs = AuthMechs.None;
434 void ParseExtensions (string extens)
436 string[] parts = extens.Split ('\n');
438 foreach (string part in parts) {
442 string start = part.Substring (4);
443 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
444 string[] options = start.Split (' ');
445 for (int k = 1; k < options.Length; k++) {
446 string option = options[k].Trim();
447 // GSSAPI, KERBEROS_V4, NTLM not supported
451 authMechs |= AuthMechs.CramMD5;
454 authMechs |= AuthMechs.DigestMD5;
458 authMechs |= AuthMechs.Login;
461 authMechs |= AuthMechs.Plain;
469 public void Send (MailMessage message)
472 throw new ArgumentNullException ("message");
474 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
475 throw new InvalidOperationException ("The SMTP host was not specified");
476 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
477 throw new NotSupportedException("IIS delivery is not supported");
482 // Block while sending
485 messageInProcess = message;
486 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
487 SendToFile (message);
489 SendInternal (message);
490 } catch (CancellationException) {
491 // This exception is introduced for convenient cancellation process.
492 } catch (SmtpException) {
494 } catch (Exception ex) {
495 throw new SmtpException ("Message could not be sent.", ex);
497 // Release the mutex to allow other threads access
498 mutex.ReleaseMutex ();
499 messageInProcess = null;
503 private void SendInternal (MailMessage message)
505 CheckCancellation ();
508 client = new TcpClient (host, port);
509 stream = client.GetStream ();
510 // FIXME: this StreamWriter creation is bogus.
511 // It expects as if a Stream were able to switch to SSL
512 // mode (such behavior is only in Mainsoft Socket API).
513 writer = new StreamWriter (stream);
514 reader = new StreamReader (stream);
529 // FIXME: simple implementation, could be brushed up.
530 private void SendToFile (MailMessage message)
532 if (!Path.IsPathRooted (pickupDirectoryLocation))
533 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
535 string filename = Path.Combine (pickupDirectoryLocation,
536 Guid.NewGuid() + ".eml");
539 writer = new StreamWriter(filename);
541 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
542 // For all we know, defaultFrom may be the envelope sender
543 // For now, we are no worse than some versions of .NET
544 MailAddress from = message.From;
548 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
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));
654 #if TARGET_JVM // List<T>.ToArray () is not supported
655 if (sfre.Count > 0) {
656 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
658 throw new SmtpFailedRecipientsException ("failed recipients", xs);
662 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
666 status = SendCommand ("DATA");
667 if (IsError (status))
668 throw new SmtpException (status.StatusCode, status.Description);
670 // Send message headers
671 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
672 // remove ':' from time zone offset (e.g. from "+01:00")
673 dt = dt.Remove (dt.Length - 3, 1);
674 SendHeader (HeaderName.Date, dt);
676 MailAddress from = message.From;
680 SendHeader (HeaderName.From, EncodeAddress (from));
681 SendHeader (HeaderName.To, EncodeAddresses (message.To));
682 if (message.CC.Count > 0)
683 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
684 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
688 switch (message.Priority){
689 case MailPriority.Normal:
693 case MailPriority.Low:
697 case MailPriority.High:
701 SendHeader ("Priority", v);
702 if (message.Sender != null)
703 SendHeader ("Sender", EncodeAddress (message.Sender));
704 if (message.ReplyToList.Count > 0)
705 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
708 foreach (string s in message.Headers.AllKeys)
709 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
711 foreach (string s in message.Headers.AllKeys)
712 SendHeader (s, message.Headers [s]);
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 private void SendDot()
743 writer.Write(".\r\n");
747 private void SendData (string data)
749 if (String.IsNullOrEmpty (data)) {
750 writer.Write("\r\n");
755 StringReader sr = new StringReader (data);
757 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
758 while ((line = sr.ReadLine ()) != null) {
759 CheckCancellation ();
763 for (i = 0; i < line.Length; i++) {
767 if (i > 0 && i == line.Length) {
772 writer.Write ("\r\n");
777 public void SendAsync (MailMessage message, object userToken)
780 throw new InvalidOperationException ("Another SendAsync operation is in progress");
782 worker = new BackgroundWorker ();
783 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
785 user_async_state = ea.Argument;
787 } catch (Exception ex) {
792 worker.WorkerSupportsCancellation = true;
793 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
794 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
795 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
797 worker.RunWorkerAsync (userToken);
800 public void SendAsync (string from, string to, string subject, string body, object userToken)
802 SendAsync (new MailMessage (from, to, subject, body), userToken);
805 public void SendAsyncCancel ()
808 throw new InvalidOperationException ("SendAsync operation is not in progress");
809 worker.CancelAsync ();
812 private void AddPriorityHeader (MailMessage message) {
813 switch (message.Priority) {
814 case MailPriority.High:
815 SendHeader (HeaderName.Priority, "Urgent");
816 SendHeader (HeaderName.Importance, "high");
817 SendHeader (HeaderName.XPriority, "1");
819 case MailPriority.Low:
820 SendHeader (HeaderName.Priority, "Non-Urgent");
821 SendHeader (HeaderName.Importance, "low");
822 SendHeader (HeaderName.XPriority, "5");
827 private void SendSimpleBody (MailMessage message) {
828 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
829 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
830 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
831 SendData (string.Empty);
833 SendData (EncodeBody (message));
836 private void SendBodylessSingleAlternate (AlternateView av) {
837 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
838 if (av.TransferEncoding != TransferEncoding.SevenBit)
839 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
840 SendData (string.Empty);
842 SendData (EncodeBody (av));
845 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
847 if (message.Body == null && message.AlternateViews.Count == 1)
848 SendBodylessSingleAlternate (message.AlternateViews [0]);
849 else if (message.AlternateViews.Count > 0)
850 SendBodyWithAlternateViews (message, boundary, attachmentExists);
852 SendSimpleBody (message);
856 private void SendWithAttachments (MailMessage message) {
857 string boundary = GenerateBoundary ();
859 // first "multipart/mixed"
860 ContentType messageContentType = new ContentType ();
861 messageContentType.Boundary = boundary;
862 messageContentType.MediaType = "multipart/mixed";
863 messageContentType.CharSet = null;
865 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
866 SendData (String.Empty);
869 Attachment body = null;
871 if (message.AlternateViews.Count > 0)
872 SendWithoutAttachments (message, boundary, true);
874 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
875 message.Attachments.Insert (0, body);
879 SendAttachments (message, body, boundary);
882 message.Attachments.Remove (body);
885 EndSection (boundary);
888 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
890 AlternateViewCollection alternateViews = message.AlternateViews;
892 string inner_boundary = GenerateBoundary ();
894 ContentType messageContentType = new ContentType ();
895 messageContentType.Boundary = inner_boundary;
896 messageContentType.MediaType = "multipart/alternative";
898 if (!attachmentExists) {
899 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
900 SendData (String.Empty);
904 AlternateView body = null;
905 if (message.Body != null) {
906 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
907 alternateViews.Insert (0, body);
908 StartSection (boundary, messageContentType);
912 // alternate view sections
913 foreach (AlternateView av in alternateViews) {
915 string alt_boundary = null;
916 ContentType contentType;
917 if (av.LinkedResources.Count > 0) {
918 alt_boundary = GenerateBoundary ();
919 contentType = new ContentType ("multipart/related");
920 contentType.Boundary = alt_boundary;
922 contentType.Parameters ["type"] = av.ContentType.ToString ();
923 StartSection (inner_boundary, contentType);
924 StartSection (alt_boundary, av.ContentType, av);
926 contentType = new ContentType (av.ContentType.ToString ());
927 StartSection (inner_boundary, contentType, av);
930 switch (av.TransferEncoding) {
931 case TransferEncoding.Base64:
932 byte [] content = new byte [av.ContentStream.Length];
933 av.ContentStream.Read (content, 0, content.Length);
935 SendData (Convert.ToBase64String (content));
937 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
940 case TransferEncoding.QuotedPrintable:
941 byte [] bytes = new byte [av.ContentStream.Length];
942 av.ContentStream.Read (bytes, 0, bytes.Length);
943 SendData (ToQuotedPrintable (bytes));
945 case TransferEncoding.SevenBit:
946 case TransferEncoding.Unknown:
947 content = new byte [av.ContentStream.Length];
948 av.ContentStream.Read (content, 0, content.Length);
949 SendData (Encoding.ASCII.GetString (content));
953 if (av.LinkedResources.Count > 0) {
954 SendLinkedResources (message, av.LinkedResources, alt_boundary);
955 EndSection (alt_boundary);
958 if (!attachmentExists)
959 SendData (string.Empty);
964 alternateViews.Remove (body);
966 EndSection (inner_boundary);
969 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
971 foreach (LinkedResource lr in resources) {
972 StartSection (boundary, lr.ContentType, lr);
974 switch (lr.TransferEncoding) {
975 case TransferEncoding.Base64:
976 byte [] content = new byte [lr.ContentStream.Length];
977 lr.ContentStream.Read (content, 0, content.Length);
979 SendData (Convert.ToBase64String (content));
981 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
984 case TransferEncoding.QuotedPrintable:
985 byte [] bytes = new byte [lr.ContentStream.Length];
986 lr.ContentStream.Read (bytes, 0, bytes.Length);
987 SendData (ToQuotedPrintable (bytes));
989 case TransferEncoding.SevenBit:
990 case TransferEncoding.Unknown:
991 content = new byte [lr.ContentStream.Length];
992 lr.ContentStream.Read (content, 0, content.Length);
993 SendData (Encoding.ASCII.GetString (content));
999 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1000 foreach (Attachment att in message.Attachments) {
1001 ContentType contentType = new ContentType (att.ContentType.ToString ());
1002 if (att.Name != null) {
1003 contentType.Name = att.Name;
1004 if (att.NameEncoding != null)
1005 contentType.CharSet = att.NameEncoding.HeaderName;
1006 att.ContentDisposition.FileName = att.Name;
1008 StartSection (boundary, contentType, att, att != body);
1010 byte [] content = new byte [att.ContentStream.Length];
1011 att.ContentStream.Read (content, 0, content.Length);
1012 switch (att.TransferEncoding) {
1013 case TransferEncoding.Base64:
1015 SendData (Convert.ToBase64String (content));
1017 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1020 case TransferEncoding.QuotedPrintable:
1021 SendData (ToQuotedPrintable (content));
1023 case TransferEncoding.SevenBit:
1024 case TransferEncoding.Unknown:
1025 SendData (Encoding.ASCII.GetString (content));
1029 SendData (string.Empty);
1033 private SmtpResponse SendCommand (string command)
1035 writer.Write (command);
1036 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1037 writer.Write ("\r\n");
1042 private void SendHeader (string name, string value)
1044 SendData (String.Format ("{0}: {1}", name, value));
1047 private void StartSection (string section, ContentType sectionContentType)
1049 SendData (String.Format ("--{0}", section));
1050 SendHeader ("content-type", sectionContentType.ToString ());
1051 SendData (string.Empty);
1054 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1056 SendData (String.Format ("--{0}", section));
1057 SendHeader ("content-type", sectionContentType.ToString ());
1058 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1059 if (!string.IsNullOrEmpty (att.ContentId))
1060 SendHeader("content-ID", "<" + att.ContentId + ">");
1061 SendData (string.Empty);
1064 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1065 SendData (String.Format ("--{0}", section));
1066 if (!string.IsNullOrEmpty (att.ContentId))
1067 SendHeader("content-ID", "<" + att.ContentId + ">");
1068 SendHeader ("content-type", sectionContentType.ToString ());
1069 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1070 if (sendDisposition)
1071 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1072 SendData (string.Empty);
1075 // use proper encoding to escape input
1076 private string ToQuotedPrintable (string input, Encoding enc)
1078 byte [] bytes = enc.GetBytes (input);
1079 return ToQuotedPrintable (bytes);
1082 private string ToQuotedPrintable (byte [] bytes)
1084 StringWriter writer = new StringWriter ();
1085 int charsInLine = 0;
1087 StringBuilder sb = new StringBuilder("=", 3);
1088 byte equalSign = (byte)'=';
1091 foreach (byte i in bytes) {
1092 if (i > 127 || i == equalSign) {
1094 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1097 c = Convert.ToChar (i);
1098 if (c == '\r' || c == '\n') {
1106 charsInLine += curLen;
1107 if (charsInLine > 75) {
1108 writer.Write ("=\r\n");
1109 charsInLine = curLen;
1114 writer.Write (sb.ToString ());
1117 return writer.ToString ();
1119 private static string GetTransferEncodingName (TransferEncoding encoding)
1122 case TransferEncoding.QuotedPrintable:
1123 return "quoted-printable";
1124 case TransferEncoding.SevenBit:
1126 case TransferEncoding.Base64:
1133 RemoteCertificateValidationCallback callback = delegate (object sender,
1134 X509Certificate certificate,
1136 SslPolicyErrors sslPolicyErrors) {
1137 // honor any exciting callback defined on ServicePointManager
1138 if (ServicePointManager.ServerCertificateValidationCallback != null)
1139 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1140 // otherwise provide our own
1141 if (sslPolicyErrors != SslPolicyErrors.None)
1142 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1147 private void InitiateSecureConnection () {
1148 SmtpResponse response = SendCommand ("STARTTLS");
1150 if (IsError (response)) {
1151 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1155 ((NetworkStream) stream).ChangeToSSLSocket ();
1157 SslStream sslStream = new SslStream (stream, false, callback, null);
1158 CheckCancellation ();
1159 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1163 throw new SystemException ("You are using an incomplete System.dll build");
1167 void Authenticate ()
1169 string user = null, pass = null;
1171 if (UseDefaultCredentials) {
1172 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1173 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1174 } else if (Credentials != null) {
1175 user = Credentials.GetCredential (host, port, "smtp").UserName;
1176 pass = Credentials.GetCredential (host, port, "smtp").Password;
1181 Authenticate (user, pass);
1184 void CheckStatus (SmtpResponse status, int i)
1186 if (((int) status.StatusCode) != i)
1187 throw new SmtpException (status.StatusCode, status.Description);
1190 void ThrowIfError (SmtpResponse status)
1192 if (IsError (status))
1193 throw new SmtpException (status.StatusCode, status.Description);
1196 void Authenticate (string user, string password)
1198 if (authMechs == AuthMechs.None)
1201 SmtpResponse status;
1203 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1204 status = SendCommand ("AUTH DIGEST-MD5");
1205 CheckStatus (status, 334);
1206 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1207 Console.WriteLine ("CHALLENGE: {0}", challenge);
1208 DigestSession session = new DigestSession ();
1209 session.Parse (false, challenge);
1210 string response = session.Authenticate (this, user, password);
1211 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1212 CheckStatus (status, 235);
1214 if ((authMechs & AuthMechs.Login) != 0) {
1215 status = SendCommand ("AUTH LOGIN");
1216 CheckStatus (status, 334);
1217 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1218 CheckStatus (status, 334);
1219 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1220 CheckStatus (status, 235);
1221 } else if ((authMechs & AuthMechs.Plain) != 0) {
1222 string s = String.Format ("\0{0}\0{1}", user, password);
1223 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1224 status = SendCommand ("AUTH PLAIN " + s);
1225 CheckStatus (status, 235);
1227 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1231 #endregion // Methods
1233 // The HeaderName struct is used to store constant string values representing mail headers.
1234 private struct HeaderName {
1235 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1236 public const string ContentType = "Content-Type";
1237 public const string Bcc = "Bcc";
1238 public const string Cc = "Cc";
1239 public const string From = "From";
1240 public const string Subject = "Subject";
1241 public const string To = "To";
1242 public const string MimeVersion = "MIME-Version";
1243 public const string MessageId = "Message-ID";
1244 public const string Priority = "Priority";
1245 public const string Importance = "Importance";
1246 public const string XPriority = "X-Priority";
1247 public const string Date = "Date";
1250 // This object encapsulates the status code and description of an SMTP response.
1251 private struct SmtpResponse {
1252 public SmtpStatusCode StatusCode;
1253 public string Description;
1255 public static SmtpResponse Parse (string line) {
1256 SmtpResponse response = new SmtpResponse ();
1258 if (line.Length < 4)
1259 throw new SmtpException ("Response is to short " +
1262 if ((line [3] != ' ') && (line [3] != '-'))
1263 throw new SmtpException ("Response format is wrong.(" +
1266 // parse the response code
1267 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1269 // set the raw response
1270 response.Description = line;
1277 class CCredentialsByHost : ICredentialsByHost
1279 public CCredentialsByHost (string userName, string password) {
1280 this.userName = userName;
1281 this.password = password;
1284 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1285 return new NetworkCredential (userName, password);
1288 private string userName;
1289 private string password;