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;
43 using System.Collections.Generic;
44 using System.ComponentModel;
45 using System.Globalization;
48 using System.Net.Mime;
49 using System.Net.Sockets;
50 using System.Security.Cryptography.X509Certificates;
52 using System.Threading;
53 using System.Reflection;
54 using System.Net.Configuration;
55 using System.Configuration;
56 using System.Net.Security;
57 using System.Security.Authentication;
59 namespace System.Net.Mail {
60 public class SmtpClient
70 ICredentialsByHost credentials;
71 string pickupDirectoryLocation;
72 SmtpDeliveryMethod deliveryMethod;
75 X509CertificateCollection clientCertificates;
83 MailAddress defaultFrom;
85 MailMessage messageInProcess;
87 BackgroundWorker worker;
88 object user_async_state;
97 class CancellationException : Exception
102 Mutex mutex = new Mutex ();
113 public SmtpClient (string host)
118 public SmtpClient (string host, int port) {
119 #if CONFIGURATION_DEP
120 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
123 this.host = cfg.Network.Host;
124 this.port = cfg.Network.Port;
126 this.enableSsl = cfg.Network.EnableSsl;
128 TargetName = cfg.Network.TargetName;
129 if (this.TargetName == null)
130 TargetName = "SMTPSVC/" + (host != null ? host : "");
133 if (cfg.Network.UserName != null) {
134 string password = String.Empty;
136 if (cfg.Network.Password != null)
137 password = cfg.Network.Password;
139 Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
142 if (!String.IsNullOrEmpty (cfg.From))
143 defaultFrom = new MailAddress (cfg.From);
146 // Just to eliminate the warning, this codepath does not end up in production.
150 if (!String.IsNullOrEmpty (host))
155 else if (this.port == 0)
159 #endregion // Constructors
164 [MonoTODO("Client certificates not used")]
165 public X509CertificateCollection ClientCertificates {
167 if (clientCertificates == null)
168 clientCertificates = new X509CertificateCollection ();
169 return clientCertificates;
177 string TargetName { get; set; }
179 public ICredentialsByHost Credentials {
180 get { return credentials; }
187 public SmtpDeliveryMethod DeliveryMethod {
188 get { return deliveryMethod; }
191 deliveryMethod = value;
195 public bool EnableSsl {
196 get { return enableSsl; }
207 throw new ArgumentNullException ("value");
208 if (value.Length == 0)
209 throw new ArgumentException ("An empty string is not allowed.", "value");
215 public string PickupDirectoryLocation {
216 get { return pickupDirectoryLocation; }
217 set { pickupDirectoryLocation = value; }
224 throw new ArgumentOutOfRangeException ("value");
231 public ServicePoint ServicePoint {
232 get { throw new NotImplementedException (); }
236 get { return timeout; }
239 throw new ArgumentOutOfRangeException ("value");
245 public bool UseDefaultCredentials {
246 get { return false; }
247 [MonoNotSupported ("no DefaultCredential support in Mono")]
250 throw new NotImplementedException ("Default credentials are not supported");
255 #endregion // Properties
259 public event SendCompletedEventHandler SendCompleted;
265 public void Dispose ()
270 [MonoTODO ("Does nothing at the moment.")]
271 protected virtual void Dispose (bool disposing)
273 // TODO: We should close all the connections and abort any async operations here
276 private void CheckState ()
278 if (messageInProcess != null)
279 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
282 private static string EncodeAddress(MailAddress address)
284 if (!String.IsNullOrEmpty (address.DisplayName)) {
285 string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
286 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
288 return address.ToString ();
291 private static string EncodeAddresses(MailAddressCollection addresses)
293 StringBuilder sb = new StringBuilder();
295 foreach (MailAddress address in addresses) {
299 sb.Append(EncodeAddress(address));
302 return sb.ToString();
305 private string EncodeSubjectRFC2047 (MailMessage message)
307 return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
310 private string EncodeBody (MailMessage message)
312 string body = message.Body;
313 Encoding encoding = message.BodyEncoding;
315 switch (message.ContentTransferEncoding) {
316 case TransferEncoding.SevenBit:
318 case TransferEncoding.Base64:
319 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
321 return ToQuotedPrintable (body, encoding);
325 private string EncodeBody (AlternateView av)
327 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
329 byte [] bytes = new byte [av.ContentStream.Length];
330 av.ContentStream.Read (bytes, 0, bytes.Length);
333 switch (av.TransferEncoding) {
334 case TransferEncoding.SevenBit:
335 return Encoding.ASCII.GetString (bytes);
336 case TransferEncoding.Base64:
337 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
339 return ToQuotedPrintable (bytes);
344 private void EndSection (string section)
346 SendData (String.Format ("--{0}--", section));
347 SendData (string.Empty);
350 private string GenerateBoundary ()
352 string output = GenerateBoundary (boundaryIndex);
357 private static string GenerateBoundary (int index)
359 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
362 private bool IsError (SmtpResponse status)
364 return ((int) status.StatusCode) >= 400;
367 protected void OnSendCompleted (AsyncCompletedEventArgs e)
370 if (SendCompleted != null)
371 SendCompleted (this, e);
374 user_async_state = null;
378 private void CheckCancellation ()
380 if (worker != null && worker.CancellationPending)
381 throw new CancellationException ();
384 private SmtpResponse Read () {
385 byte [] buffer = new byte [512];
387 bool lastLine = false;
390 CheckCancellation ();
392 int readLength = stream.Read (buffer, position, buffer.Length - position);
393 if (readLength > 0) {
394 int available = position + readLength - 1;
395 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
396 for (int index = available - 3; ; index--) {
397 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
398 lastLine = buffer [index + 4] == ' ';
404 position += readLength;
406 // check if buffer is full
407 if (position == buffer.Length) {
408 byte [] newBuffer = new byte [buffer.Length * 2];
409 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
419 Encoding encoding = new ASCIIEncoding ();
421 string line = encoding.GetString (buffer, 0, position - 1);
423 // parse the line to the lastResponse object
424 SmtpResponse response = SmtpResponse.Parse (line);
428 throw new System.IO.IOException ("Connection closed");
432 void ResetExtensions()
434 authMechs = AuthMechs.None;
437 void ParseExtensions (string extens)
439 string[] parts = extens.Split ('\n');
441 foreach (string part in parts) {
445 string start = part.Substring (4);
446 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
447 string[] options = start.Split (' ');
448 for (int k = 1; k < options.Length; k++) {
449 string option = options[k].Trim();
450 // GSSAPI, KERBEROS_V4, NTLM not supported
454 authMechs |= AuthMechs.CramMD5;
457 authMechs |= AuthMechs.DigestMD5;
461 authMechs |= AuthMechs.Login;
464 authMechs |= AuthMechs.Plain;
472 public void Send (MailMessage message)
475 throw new ArgumentNullException ("message");
477 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
478 throw new InvalidOperationException ("The SMTP host was not specified");
479 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
480 throw new NotSupportedException("IIS delivery is not supported");
485 // Block while sending
488 messageInProcess = message;
489 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
490 SendToFile (message);
492 SendInternal (message);
493 } catch (CancellationException) {
494 // This exception is introduced for convenient cancellation process.
495 } catch (SmtpException) {
497 } catch (Exception ex) {
498 throw new SmtpException ("Message could not be sent.", ex);
500 // Release the mutex to allow other threads access
501 mutex.ReleaseMutex ();
502 messageInProcess = null;
506 private void SendInternal (MailMessage message)
508 CheckCancellation ();
511 client = new TcpClient (host, port);
512 stream = client.GetStream ();
513 // FIXME: this StreamWriter creation is bogus.
514 // It expects as if a Stream were able to switch to SSL
515 // mode (such behavior is only in Mainsoft Socket API).
516 writer = new StreamWriter (stream);
517 reader = new StreamReader (stream);
532 // FIXME: simple implementation, could be brushed up.
533 private void SendToFile (MailMessage message)
535 if (!Path.IsPathRooted (pickupDirectoryLocation))
536 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
538 string filename = Path.Combine (pickupDirectoryLocation,
539 Guid.NewGuid() + ".eml");
542 writer = new StreamWriter(filename);
544 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
545 // For all we know, defaultFrom may be the envelope sender
546 // For now, we are no worse than some versions of .NET
547 MailAddress from = message.From;
551 SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
552 SendHeader (HeaderName.From, EncodeAddress(from));
553 SendHeader (HeaderName.To, EncodeAddresses(message.To));
554 if (message.CC.Count > 0)
555 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
556 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
558 foreach (string s in message.Headers.AllKeys)
559 SendHeader (s, message.Headers [s]);
561 AddPriorityHeader (message);
564 if (message.Attachments.Count > 0)
565 SendWithAttachments (message);
567 SendWithoutAttachments (message, null, false);
571 if (writer != null) writer.Close(); writer = null;
575 private void SendCore (MailMessage message)
580 if (IsError (status))
581 throw new SmtpException (status.StatusCode, status.Description);
585 // FIXME: parse the list of extensions so we don't bother wasting
586 // our time trying commands if they aren't supported.
587 status = SendCommand ("EHLO " + Dns.GetHostName ());
589 if (IsError (status)) {
590 status = SendCommand ("HELO " + Dns.GetHostName ());
592 if (IsError (status))
593 throw new SmtpException (status.StatusCode, status.Description);
595 // Parse ESMTP extensions
596 string extens = status.Description;
599 ParseExtensions (extens);
603 InitiateSecureConnection ();
605 writer = new StreamWriter (stream);
606 reader = new StreamReader (stream);
607 status = SendCommand ("EHLO " + Dns.GetHostName ());
609 if (IsError (status)) {
610 status = SendCommand ("HELO " + Dns.GetHostName ());
612 if (IsError (status))
613 throw new SmtpException (status.StatusCode, status.Description);
615 // Parse ESMTP extensions
616 string extens = status.Description;
618 ParseExtensions (extens);
622 if (authMechs != AuthMechs.None)
625 // The envelope sender: use 'Sender:' in preference of 'From:'
626 MailAddress sender = message.Sender;
628 sender = message.From;
630 sender = defaultFrom;
633 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
634 if (IsError (status)) {
635 throw new SmtpException (status.StatusCode, status.Description);
638 // Send RCPT TO: for all recipients
639 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
641 for (int i = 0; i < message.To.Count; i ++) {
642 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
643 if (IsError (status))
644 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
646 for (int i = 0; i < message.CC.Count; i ++) {
647 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
648 if (IsError (status))
649 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
651 for (int i = 0; i < message.Bcc.Count; i ++) {
652 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
653 if (IsError (status))
654 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
657 #if TARGET_JVM // List<T>.ToArray () is not supported
658 if (sfre.Count > 0) {
659 SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
661 throw new SmtpFailedRecipientsException ("failed recipients", xs);
665 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
669 status = SendCommand ("DATA");
670 if (IsError (status))
671 throw new SmtpException (status.StatusCode, status.Description);
673 // Send message headers
674 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
675 // remove ':' from time zone offset (e.g. from "+01:00")
676 dt = dt.Remove (dt.Length - 3, 1);
677 SendHeader (HeaderName.Date, dt);
679 MailAddress from = message.From;
683 SendHeader (HeaderName.From, EncodeAddress (from));
684 SendHeader (HeaderName.To, EncodeAddresses (message.To));
685 if (message.CC.Count > 0)
686 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
687 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
691 switch (message.Priority){
692 case MailPriority.Normal:
696 case MailPriority.Low:
700 case MailPriority.High:
704 SendHeader ("Priority", v);
705 if (message.Sender != null)
706 SendHeader ("Sender", EncodeAddress (message.Sender));
707 if (message.ReplyToList.Count > 0)
708 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
711 foreach (string s in message.Headers.AllKeys)
712 SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
714 foreach (string s in message.Headers.AllKeys)
715 SendHeader (s, message.Headers [s]);
718 AddPriorityHeader (message);
721 if (message.Attachments.Count > 0)
722 SendWithAttachments (message);
724 SendWithoutAttachments (message, null, false);
729 if (IsError (status))
730 throw new SmtpException (status.StatusCode, status.Description);
733 status = SendCommand ("QUIT");
734 } catch (System.IO.IOException) {
735 // We excuse server for the rude connection closing as a response to QUIT
739 public void Send (string from, string to, string subject, string body)
741 Send (new MailMessage (from, to, subject, body));
744 private void SendDot()
746 writer.Write(".\r\n");
750 private void SendData (string data)
752 if (String.IsNullOrEmpty (data)) {
753 writer.Write("\r\n");
758 StringReader sr = new StringReader (data);
760 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
761 while ((line = sr.ReadLine ()) != null) {
762 CheckCancellation ();
766 for (i = 0; i < line.Length; i++) {
770 if (i > 0 && i == line.Length) {
775 writer.Write ("\r\n");
780 public void SendAsync (MailMessage message, object userToken)
783 throw new InvalidOperationException ("Another SendAsync operation is in progress");
785 worker = new BackgroundWorker ();
786 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
788 user_async_state = ea.Argument;
790 } catch (Exception ex) {
795 worker.WorkerSupportsCancellation = true;
796 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
797 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
798 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
800 worker.RunWorkerAsync (userToken);
803 public void SendAsync (string from, string to, string subject, string body, object userToken)
805 SendAsync (new MailMessage (from, to, subject, body), userToken);
808 public void SendAsyncCancel ()
811 throw new InvalidOperationException ("SendAsync operation is not in progress");
812 worker.CancelAsync ();
815 private void AddPriorityHeader (MailMessage message) {
816 switch (message.Priority) {
817 case MailPriority.High:
818 SendHeader (HeaderName.Priority, "Urgent");
819 SendHeader (HeaderName.Importance, "high");
820 SendHeader (HeaderName.XPriority, "1");
822 case MailPriority.Low:
823 SendHeader (HeaderName.Priority, "Non-Urgent");
824 SendHeader (HeaderName.Importance, "low");
825 SendHeader (HeaderName.XPriority, "5");
830 private void SendSimpleBody (MailMessage message) {
831 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
832 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
833 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
834 SendData (string.Empty);
836 SendData (EncodeBody (message));
839 private void SendBodylessSingleAlternate (AlternateView av) {
840 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
841 if (av.TransferEncoding != TransferEncoding.SevenBit)
842 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
843 SendData (string.Empty);
845 SendData (EncodeBody (av));
848 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
850 if (message.Body == null && message.AlternateViews.Count == 1)
851 SendBodylessSingleAlternate (message.AlternateViews [0]);
852 else if (message.AlternateViews.Count > 0)
853 SendBodyWithAlternateViews (message, boundary, attachmentExists);
855 SendSimpleBody (message);
859 private void SendWithAttachments (MailMessage message) {
860 string boundary = GenerateBoundary ();
862 // first "multipart/mixed"
863 ContentType messageContentType = new ContentType ();
864 messageContentType.Boundary = boundary;
865 messageContentType.MediaType = "multipart/mixed";
866 messageContentType.CharSet = null;
868 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
869 SendData (String.Empty);
872 Attachment body = null;
874 if (message.AlternateViews.Count > 0)
875 SendWithoutAttachments (message, boundary, true);
877 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
878 message.Attachments.Insert (0, body);
882 SendAttachments (message, body, boundary);
885 message.Attachments.Remove (body);
888 EndSection (boundary);
891 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
893 AlternateViewCollection alternateViews = message.AlternateViews;
895 string inner_boundary = GenerateBoundary ();
897 ContentType messageContentType = new ContentType ();
898 messageContentType.Boundary = inner_boundary;
899 messageContentType.MediaType = "multipart/alternative";
901 if (!attachmentExists) {
902 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
903 SendData (String.Empty);
907 AlternateView body = null;
908 if (message.Body != null) {
909 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
910 alternateViews.Insert (0, body);
911 StartSection (boundary, messageContentType);
915 // alternate view sections
916 foreach (AlternateView av in alternateViews) {
918 string alt_boundary = null;
919 ContentType contentType;
920 if (av.LinkedResources.Count > 0) {
921 alt_boundary = GenerateBoundary ();
922 contentType = new ContentType ("multipart/related");
923 contentType.Boundary = alt_boundary;
925 contentType.Parameters ["type"] = av.ContentType.ToString ();
926 StartSection (inner_boundary, contentType);
927 StartSection (alt_boundary, av.ContentType, av);
929 contentType = new ContentType (av.ContentType.ToString ());
930 StartSection (inner_boundary, contentType, av);
933 switch (av.TransferEncoding) {
934 case TransferEncoding.Base64:
935 byte [] content = new byte [av.ContentStream.Length];
936 av.ContentStream.Read (content, 0, content.Length);
938 SendData (Convert.ToBase64String (content));
940 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
943 case TransferEncoding.QuotedPrintable:
944 byte [] bytes = new byte [av.ContentStream.Length];
945 av.ContentStream.Read (bytes, 0, bytes.Length);
946 SendData (ToQuotedPrintable (bytes));
948 case TransferEncoding.SevenBit:
949 case TransferEncoding.Unknown:
950 content = new byte [av.ContentStream.Length];
951 av.ContentStream.Read (content, 0, content.Length);
952 SendData (Encoding.ASCII.GetString (content));
956 if (av.LinkedResources.Count > 0) {
957 SendLinkedResources (message, av.LinkedResources, alt_boundary);
958 EndSection (alt_boundary);
961 if (!attachmentExists)
962 SendData (string.Empty);
967 alternateViews.Remove (body);
969 EndSection (inner_boundary);
972 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
974 foreach (LinkedResource lr in resources) {
975 StartSection (boundary, lr.ContentType, lr);
977 switch (lr.TransferEncoding) {
978 case TransferEncoding.Base64:
979 byte [] content = new byte [lr.ContentStream.Length];
980 lr.ContentStream.Read (content, 0, content.Length);
982 SendData (Convert.ToBase64String (content));
984 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
987 case TransferEncoding.QuotedPrintable:
988 byte [] bytes = new byte [lr.ContentStream.Length];
989 lr.ContentStream.Read (bytes, 0, bytes.Length);
990 SendData (ToQuotedPrintable (bytes));
992 case TransferEncoding.SevenBit:
993 case TransferEncoding.Unknown:
994 content = new byte [lr.ContentStream.Length];
995 lr.ContentStream.Read (content, 0, content.Length);
996 SendData (Encoding.ASCII.GetString (content));
1002 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1003 foreach (Attachment att in message.Attachments) {
1004 ContentType contentType = new ContentType (att.ContentType.ToString ());
1005 if (att.Name != null) {
1006 contentType.Name = att.Name;
1007 if (att.NameEncoding != null)
1008 contentType.CharSet = att.NameEncoding.HeaderName;
1009 att.ContentDisposition.FileName = att.Name;
1011 StartSection (boundary, contentType, att, att != body);
1013 byte [] content = new byte [att.ContentStream.Length];
1014 att.ContentStream.Read (content, 0, content.Length);
1015 switch (att.TransferEncoding) {
1016 case TransferEncoding.Base64:
1018 SendData (Convert.ToBase64String (content));
1020 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1023 case TransferEncoding.QuotedPrintable:
1024 SendData (ToQuotedPrintable (content));
1026 case TransferEncoding.SevenBit:
1027 case TransferEncoding.Unknown:
1028 SendData (Encoding.ASCII.GetString (content));
1032 SendData (string.Empty);
1036 private SmtpResponse SendCommand (string command)
1038 writer.Write (command);
1039 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1040 writer.Write ("\r\n");
1045 private void SendHeader (string name, string value)
1047 SendData (String.Format ("{0}: {1}", name, value));
1050 private void StartSection (string section, ContentType sectionContentType)
1052 SendData (String.Format ("--{0}", section));
1053 SendHeader ("content-type", sectionContentType.ToString ());
1054 SendData (string.Empty);
1057 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1059 SendData (String.Format ("--{0}", section));
1060 SendHeader ("content-type", sectionContentType.ToString ());
1061 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1062 if (!string.IsNullOrEmpty (att.ContentId))
1063 SendHeader("content-ID", "<" + att.ContentId + ">");
1064 SendData (string.Empty);
1067 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1068 SendData (String.Format ("--{0}", section));
1069 if (!string.IsNullOrEmpty (att.ContentId))
1070 SendHeader("content-ID", "<" + att.ContentId + ">");
1071 SendHeader ("content-type", sectionContentType.ToString ());
1072 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1073 if (sendDisposition)
1074 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1075 SendData (string.Empty);
1078 // use proper encoding to escape input
1079 private string ToQuotedPrintable (string input, Encoding enc)
1081 byte [] bytes = enc.GetBytes (input);
1082 return ToQuotedPrintable (bytes);
1085 private string ToQuotedPrintable (byte [] bytes)
1087 StringWriter writer = new StringWriter ();
1088 int charsInLine = 0;
1090 StringBuilder sb = new StringBuilder("=", 3);
1091 byte equalSign = (byte)'=';
1094 foreach (byte i in bytes) {
1095 if (i > 127 || i == equalSign) {
1097 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1100 c = Convert.ToChar (i);
1101 if (c == '\r' || c == '\n') {
1109 charsInLine += curLen;
1110 if (charsInLine > 75) {
1111 writer.Write ("=\r\n");
1112 charsInLine = curLen;
1117 writer.Write (sb.ToString ());
1120 return writer.ToString ();
1122 private static string GetTransferEncodingName (TransferEncoding encoding)
1125 case TransferEncoding.QuotedPrintable:
1126 return "quoted-printable";
1127 case TransferEncoding.SevenBit:
1129 case TransferEncoding.Base64:
1136 RemoteCertificateValidationCallback callback = delegate (object sender,
1137 X509Certificate certificate,
1139 SslPolicyErrors sslPolicyErrors) {
1140 // honor any exciting callback defined on ServicePointManager
1141 if (ServicePointManager.ServerCertificateValidationCallback != null)
1142 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1143 // otherwise provide our own
1144 if (sslPolicyErrors != SslPolicyErrors.None)
1145 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1150 private void InitiateSecureConnection () {
1151 SmtpResponse response = SendCommand ("STARTTLS");
1153 if (IsError (response)) {
1154 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1158 ((NetworkStream) stream).ChangeToSSLSocket ();
1160 SslStream sslStream = new SslStream (stream, false, callback, null);
1161 CheckCancellation ();
1162 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1166 throw new SystemException ("You are using an incomplete System.dll build");
1170 void Authenticate ()
1172 string user = null, pass = null;
1174 if (UseDefaultCredentials) {
1175 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1176 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1177 } else if (Credentials != null) {
1178 user = Credentials.GetCredential (host, port, "smtp").UserName;
1179 pass = Credentials.GetCredential (host, port, "smtp").Password;
1184 Authenticate (user, pass);
1187 void CheckStatus (SmtpResponse status, int i)
1189 if (((int) status.StatusCode) != i)
1190 throw new SmtpException (status.StatusCode, status.Description);
1193 void ThrowIfError (SmtpResponse status)
1195 if (IsError (status))
1196 throw new SmtpException (status.StatusCode, status.Description);
1199 void Authenticate (string user, string password)
1201 if (authMechs == AuthMechs.None)
1204 SmtpResponse status;
1206 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1207 status = SendCommand ("AUTH DIGEST-MD5");
1208 CheckStatus (status, 334);
1209 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1210 Console.WriteLine ("CHALLENGE: {0}", challenge);
1211 DigestSession session = new DigestSession ();
1212 session.Parse (false, challenge);
1213 string response = session.Authenticate (this, user, password);
1214 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1215 CheckStatus (status, 235);
1217 if ((authMechs & AuthMechs.Login) != 0) {
1218 status = SendCommand ("AUTH LOGIN");
1219 CheckStatus (status, 334);
1220 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1221 CheckStatus (status, 334);
1222 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1223 CheckStatus (status, 235);
1224 } else if ((authMechs & AuthMechs.Plain) != 0) {
1225 string s = String.Format ("\0{0}\0{1}", user, password);
1226 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1227 status = SendCommand ("AUTH PLAIN " + s);
1228 CheckStatus (status, 235);
1230 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1234 #endregion // Methods
1236 // The HeaderName struct is used to store constant string values representing mail headers.
1237 private struct HeaderName {
1238 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1239 public const string ContentType = "Content-Type";
1240 public const string Bcc = "Bcc";
1241 public const string Cc = "Cc";
1242 public const string From = "From";
1243 public const string Subject = "Subject";
1244 public const string To = "To";
1245 public const string MimeVersion = "MIME-Version";
1246 public const string MessageId = "Message-ID";
1247 public const string Priority = "Priority";
1248 public const string Importance = "Importance";
1249 public const string XPriority = "X-Priority";
1250 public const string Date = "Date";
1253 // This object encapsulates the status code and description of an SMTP response.
1254 private struct SmtpResponse {
1255 public SmtpStatusCode StatusCode;
1256 public string Description;
1258 public static SmtpResponse Parse (string line) {
1259 SmtpResponse response = new SmtpResponse ();
1261 if (line.Length < 4)
1262 throw new SmtpException ("Response is to short " +
1265 if ((line [3] != ' ') && (line [3] != '-'))
1266 throw new SmtpException ("Response format is wrong.(" +
1269 // parse the response code
1270 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1272 // set the raw response
1273 response.Description = line;
1280 class CCredentialsByHost : ICredentialsByHost
1282 public CCredentialsByHost (string userName, string password) {
1283 this.userName = userName;
1284 this.password = password;
1287 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1288 return new NetworkCredential (userName, password);
1291 private string userName;
1292 private string password;