2 // System.Net.Mail.SmtpClient.cs
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2004
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 #if MONO_SECURITY_ALIAS
33 extern alias MonoSecurity;
36 #if MONO_SECURITY_ALIAS
37 using MSI = MonoSecurity::Mono.Security.Interface;
39 using MSI = Mono.Security.Interface;
41 using System.Security.Cryptography.X509Certificates;
45 using System.Collections.Generic;
46 using System.ComponentModel;
47 using System.Globalization;
50 using System.Net.Mime;
51 using System.Net.Sockets;
53 using System.Threading;
54 using System.Net.Configuration;
55 using System.Configuration;
56 using System.Net.Security;
57 using System.Security.Authentication;
58 using System.Threading.Tasks;
59 using Mono.Net.Security;
61 namespace System.Net.Mail {
62 [Obsolete ("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
63 public class SmtpClient
71 ICredentialsByHost credentials;
72 string pickupDirectoryLocation;
73 SmtpDeliveryMethod deliveryMethod;
74 SmtpDeliveryFormat deliveryFormat;
77 X509CertificateCollection clientCertificates;
85 MailAddress defaultFrom;
87 MailMessage messageInProcess;
89 BackgroundWorker worker;
90 object user_async_state;
99 class CancellationException : Exception
104 Mutex mutex = new Mutex ();
115 public SmtpClient (string host)
120 public SmtpClient (string host, int port) {
121 #if CONFIGURATION_DEP
122 SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
125 this.host = cfg.Network.Host;
126 this.port = cfg.Network.Port;
127 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;
175 string TargetName { get; set; }
177 public ICredentialsByHost Credentials {
178 get { return credentials; }
185 public SmtpDeliveryMethod DeliveryMethod {
186 get { return deliveryMethod; }
189 deliveryMethod = value;
193 public bool EnableSsl {
194 get { return enableSsl; }
205 throw new ArgumentNullException ("value");
206 if (value.Length == 0)
207 throw new ArgumentException ("An empty string is not allowed.", "value");
213 public string PickupDirectoryLocation {
214 get { return pickupDirectoryLocation; }
215 set { pickupDirectoryLocation = value; }
222 throw new ArgumentOutOfRangeException ("value");
228 public SmtpDeliveryFormat DeliveryFormat {
229 get { return deliveryFormat; }
232 deliveryFormat = value;
237 public ServicePoint ServicePoint {
238 get { throw new NotImplementedException (); }
242 get { return timeout; }
245 throw new ArgumentOutOfRangeException ("value");
251 public bool UseDefaultCredentials {
252 get { return false; }
253 [MonoNotSupported ("no DefaultCredential support in Mono")]
256 throw new NotImplementedException ("Default credentials are not supported");
261 #endregion // Properties
265 public event SendCompletedEventHandler SendCompleted;
270 public void Dispose ()
275 [MonoTODO ("Does nothing at the moment.")]
276 protected virtual void Dispose (bool disposing)
278 // TODO: We should close all the connections and abort any async operations here
280 private void CheckState ()
282 if (messageInProcess != null)
283 throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
286 private static string EncodeAddress(MailAddress address)
288 if (!String.IsNullOrEmpty (address.DisplayName)) {
289 string encodedDisplayName = MailMessage.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
290 return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
292 return address.ToString ();
295 private static string EncodeAddresses(MailAddressCollection addresses)
297 StringBuilder sb = new StringBuilder();
299 foreach (MailAddress address in addresses) {
303 sb.Append(EncodeAddress(address));
306 return sb.ToString();
309 private string EncodeSubjectRFC2047 (MailMessage message)
311 return MailMessage.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
314 private string EncodeBody (MailMessage message)
316 string body = message.Body;
317 Encoding encoding = message.BodyEncoding;
319 switch (message.ContentTransferEncoding) {
320 case TransferEncoding.SevenBit:
322 case TransferEncoding.Base64:
323 return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
325 return ToQuotedPrintable (body, encoding);
329 private string EncodeBody (AlternateView av)
331 //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
333 byte [] bytes = new byte [av.ContentStream.Length];
334 av.ContentStream.Read (bytes, 0, bytes.Length);
337 switch (av.TransferEncoding) {
338 case TransferEncoding.SevenBit:
339 return Encoding.ASCII.GetString (bytes);
340 case TransferEncoding.Base64:
341 return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
343 return ToQuotedPrintable (bytes);
348 private void EndSection (string section)
350 SendData (String.Format ("--{0}--", section));
351 SendData (string.Empty);
354 private string GenerateBoundary ()
356 string output = GenerateBoundary (boundaryIndex);
361 private static string GenerateBoundary (int index)
363 return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
366 private bool IsError (SmtpResponse status)
368 return ((int) status.StatusCode) >= 400;
371 protected void OnSendCompleted (AsyncCompletedEventArgs e)
374 if (SendCompleted != null)
375 SendCompleted (this, e);
378 user_async_state = null;
382 private void CheckCancellation ()
384 if (worker != null && worker.CancellationPending)
385 throw new CancellationException ();
388 private SmtpResponse Read () {
389 byte [] buffer = new byte [512];
391 bool lastLine = false;
394 CheckCancellation ();
396 int readLength = stream.Read (buffer, position, buffer.Length - position);
397 if (readLength > 0) {
398 int available = position + readLength - 1;
399 if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
400 for (int index = available - 3; ; index--) {
401 if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
402 lastLine = buffer [index + 4] == ' ';
408 position += readLength;
410 // check if buffer is full
411 if (position == buffer.Length) {
412 byte [] newBuffer = new byte [buffer.Length * 2];
413 Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
423 Encoding encoding = new ASCIIEncoding ();
425 string line = encoding.GetString (buffer, 0, position - 1);
427 // parse the line to the lastResponse object
428 SmtpResponse response = SmtpResponse.Parse (line);
432 throw new System.IO.IOException ("Connection closed");
436 void ResetExtensions()
438 authMechs = AuthMechs.None;
441 void ParseExtensions (string extens)
443 string[] parts = extens.Split ('\n');
445 foreach (string part in parts) {
449 string start = part.Substring (4);
450 if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
451 string[] options = start.Split (' ');
452 for (int k = 1; k < options.Length; k++) {
453 string option = options[k].Trim();
454 // GSSAPI, KERBEROS_V4, NTLM not supported
458 authMechs |= AuthMechs.CramMD5;
461 authMechs |= AuthMechs.DigestMD5;
465 authMechs |= AuthMechs.Login;
468 authMechs |= AuthMechs.Plain;
476 public void Send (MailMessage message)
479 throw new ArgumentNullException ("message");
481 if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
482 throw new InvalidOperationException ("The SMTP host was not specified");
483 else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
484 throw new NotSupportedException("IIS delivery is not supported");
489 // Block while sending
492 messageInProcess = message;
493 if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
494 SendToFile (message);
496 SendInternal (message);
497 } catch (CancellationException) {
498 // This exception is introduced for convenient cancellation process.
499 } catch (SmtpException) {
501 } catch (Exception ex) {
502 throw new SmtpException ("Message could not be sent.", ex);
504 // Release the mutex to allow other threads access
505 mutex.ReleaseMutex ();
506 messageInProcess = null;
510 private void SendInternal (MailMessage message)
512 CheckCancellation ();
515 client = new TcpClient (host, port);
516 stream = client.GetStream ();
517 // FIXME: this StreamWriter creation is bogus.
518 // It expects as if a Stream were able to switch to SSL
519 // mode (such behavior is only in Mainsoft Socket API).
520 writer = new StreamWriter (stream);
521 reader = new StreamReader (stream);
536 // FIXME: simple implementation, could be brushed up.
537 private void SendToFile (MailMessage message)
539 if (!Path.IsPathRooted (pickupDirectoryLocation))
540 throw new SmtpException("Only absolute directories are allowed for pickup directory.");
542 string filename = Path.Combine (pickupDirectoryLocation,
543 Guid.NewGuid() + ".eml");
546 writer = new StreamWriter(filename);
548 // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
549 // For all we know, defaultFrom may be the envelope sender
550 // For now, we are no worse than some versions of .NET
551 MailAddress from = message.From;
555 string dt = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
556 // remove ':' from time zone offset (e.g. from "+01:00")
557 dt = dt.Remove(dt.Length - 3, 1);
558 SendHeader(HeaderName.Date, dt);
560 SendHeader (HeaderName.From, EncodeAddress(from));
561 SendHeader (HeaderName.To, EncodeAddresses(message.To));
562 if (message.CC.Count > 0)
563 SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
564 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
566 foreach (string s in message.Headers.AllKeys)
567 SendHeader (s, message.Headers [s]);
569 AddPriorityHeader (message);
572 if (message.Attachments.Count > 0)
573 SendWithAttachments (message);
575 SendWithoutAttachments (message, null, false);
579 if (writer != null) writer.Close(); writer = null;
583 private void SendCore (MailMessage message)
588 if (IsError (status))
589 throw new SmtpException (status.StatusCode, status.Description);
593 // FIXME: parse the list of extensions so we don't bother wasting
594 // our time trying commands if they aren't supported.
596 // get the host name (not fully qualified)
597 string fqdn = Dns.GetHostName ();
599 // we'll try for the fully qualified name - ref: bug #33551
600 fqdn = Dns.GetHostEntry (fqdn).HostName;
602 catch (SocketException) {
603 // we could not resolve our name but will continue with the partial name
604 // IOW we won't fail to send email because of this - ref: bug #37246
606 status = SendCommand ("EHLO " + fqdn);
608 if (IsError (status)) {
609 status = SendCommand ("HELO " + fqdn);
611 if (IsError (status))
612 throw new SmtpException (status.StatusCode, status.Description);
614 // Parse ESMTP extensions
615 string extens = status.Description;
618 ParseExtensions (extens);
622 InitiateSecureConnection ();
624 writer = new StreamWriter (stream);
625 reader = new StreamReader (stream);
626 status = SendCommand ("EHLO " + fqdn);
628 if (IsError (status)) {
629 status = SendCommand ("HELO " + fqdn);
631 if (IsError (status))
632 throw new SmtpException (status.StatusCode, status.Description);
634 // Parse ESMTP extensions
635 string extens = status.Description;
637 ParseExtensions (extens);
641 if (authMechs != AuthMechs.None)
644 // The envelope sender: use 'Sender:' in preference of 'From:'
645 MailAddress sender = message.Sender;
647 sender = message.From;
649 sender = defaultFrom;
652 status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
653 if (IsError (status)) {
654 throw new SmtpException (status.StatusCode, status.Description);
657 // Send RCPT TO: for all recipients
658 List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
660 for (int i = 0; i < message.To.Count; i ++) {
661 status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
662 if (IsError (status))
663 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
665 for (int i = 0; i < message.CC.Count; i ++) {
666 status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
667 if (IsError (status))
668 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
670 for (int i = 0; i < message.Bcc.Count; i ++) {
671 status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
672 if (IsError (status))
673 sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
677 throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
680 status = SendCommand ("DATA");
681 if (IsError (status))
682 throw new SmtpException (status.StatusCode, status.Description);
684 // Send message headers
685 string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
686 // remove ':' from time zone offset (e.g. from "+01:00")
687 dt = dt.Remove (dt.Length - 3, 1);
688 SendHeader (HeaderName.Date, dt);
690 MailAddress from = message.From;
694 SendHeader (HeaderName.From, EncodeAddress (from));
695 SendHeader (HeaderName.To, EncodeAddresses (message.To));
696 if (message.CC.Count > 0)
697 SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
698 SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
702 switch (message.Priority){
703 case MailPriority.Normal:
707 case MailPriority.Low:
711 case MailPriority.High:
715 SendHeader ("Priority", v);
716 if (message.Sender != null)
717 SendHeader ("Sender", EncodeAddress (message.Sender));
718 if (message.ReplyToList.Count > 0)
719 SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
721 foreach (string s in message.Headers.AllKeys)
722 SendHeader (s, MailMessage.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
724 AddPriorityHeader (message);
727 if (message.Attachments.Count > 0)
728 SendWithAttachments (message);
730 SendWithoutAttachments (message, null, false);
735 if (IsError (status))
736 throw new SmtpException (status.StatusCode, status.Description);
739 status = SendCommand ("QUIT");
740 } catch (System.IO.IOException) {
741 // We excuse server for the rude connection closing as a response to QUIT
745 public void Send (string from, string recipients, string subject, string body)
747 Send (new MailMessage (from, recipients, subject, body));
750 public Task SendMailAsync (MailMessage message)
752 var tcs = new TaskCompletionSource<object> ();
753 SendCompletedEventHandler handler = null;
754 handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
755 SendCompleted += handler;
756 SendAsync (message, tcs);
760 public Task SendMailAsync (string from, string recipients, string subject, string body)
762 return SendMailAsync (new MailMessage (from, recipients, subject, body));
765 static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
767 if (source != e.UserState)
770 client.SendCompleted -= handler;
772 if (e.Error != null) {
773 source.SetException (e.Error);
778 source.SetCanceled ();
782 source.SetResult (null);
785 private void SendDot()
787 writer.Write(".\r\n");
791 private void SendData (string data)
793 if (String.IsNullOrEmpty (data)) {
794 writer.Write("\r\n");
799 StringReader sr = new StringReader (data);
801 bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
802 while ((line = sr.ReadLine ()) != null) {
803 CheckCancellation ();
806 if (line.Length > 0 && line[0] == '.') {
811 writer.Write ("\r\n");
816 public void SendAsync (MailMessage message, object userToken)
819 throw new InvalidOperationException ("Another SendAsync operation is in progress");
821 worker = new BackgroundWorker ();
822 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
824 user_async_state = ea.Argument;
826 } catch (Exception ex) {
831 worker.WorkerSupportsCancellation = true;
832 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
833 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
834 OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
836 worker.RunWorkerAsync (userToken);
839 public void SendAsync (string from, string recipients, string subject, string body, object userToken)
841 SendAsync (new MailMessage (from, recipients, subject, body), userToken);
844 public void SendAsyncCancel ()
847 throw new InvalidOperationException ("SendAsync operation is not in progress");
848 worker.CancelAsync ();
851 private void AddPriorityHeader (MailMessage message) {
852 switch (message.Priority) {
853 case MailPriority.High:
854 SendHeader (HeaderName.Priority, "Urgent");
855 SendHeader (HeaderName.Importance, "high");
856 SendHeader (HeaderName.XPriority, "1");
858 case MailPriority.Low:
859 SendHeader (HeaderName.Priority, "Non-Urgent");
860 SendHeader (HeaderName.Importance, "low");
861 SendHeader (HeaderName.XPriority, "5");
866 private void SendSimpleBody (MailMessage message) {
867 SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
868 if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
869 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
870 SendData (string.Empty);
872 SendData (EncodeBody (message));
875 private void SendBodylessSingleAlternate (AlternateView av) {
876 SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
877 if (av.TransferEncoding != TransferEncoding.SevenBit)
878 SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
879 SendData (string.Empty);
881 SendData (EncodeBody (av));
884 private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
886 if (message.Body == null && message.AlternateViews.Count == 1)
887 SendBodylessSingleAlternate (message.AlternateViews [0]);
888 else if (message.AlternateViews.Count > 0)
889 SendBodyWithAlternateViews (message, boundary, attachmentExists);
891 SendSimpleBody (message);
895 private void SendWithAttachments (MailMessage message) {
896 string boundary = GenerateBoundary ();
898 // first "multipart/mixed"
899 ContentType messageContentType = new ContentType ();
900 messageContentType.Boundary = boundary;
901 messageContentType.MediaType = "multipart/mixed";
902 messageContentType.CharSet = null;
904 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
905 SendData (String.Empty);
908 Attachment body = null;
910 if (message.AlternateViews.Count > 0)
911 SendWithoutAttachments (message, boundary, true);
913 body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
914 message.Attachments.Insert (0, body);
918 SendAttachments (message, body, boundary);
921 message.Attachments.Remove (body);
924 EndSection (boundary);
927 private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
929 AlternateViewCollection alternateViews = message.AlternateViews;
931 string inner_boundary = GenerateBoundary ();
933 ContentType messageContentType = new ContentType ();
934 messageContentType.Boundary = inner_boundary;
935 messageContentType.MediaType = "multipart/alternative";
937 if (!attachmentExists) {
938 SendHeader (HeaderName.ContentType, messageContentType.ToString ());
939 SendData (String.Empty);
943 AlternateView body = null;
944 if (message.Body != null) {
945 body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
946 alternateViews.Insert (0, body);
947 StartSection (boundary, messageContentType);
951 // alternate view sections
952 foreach (AlternateView av in alternateViews) {
954 string alt_boundary = null;
955 ContentType contentType;
956 if (av.LinkedResources.Count > 0) {
957 alt_boundary = GenerateBoundary ();
958 contentType = new ContentType ("multipart/related");
959 contentType.Boundary = alt_boundary;
961 contentType.Parameters ["type"] = av.ContentType.ToString ();
962 StartSection (inner_boundary, contentType);
963 StartSection (alt_boundary, av.ContentType, av);
965 contentType = new ContentType (av.ContentType.ToString ());
966 StartSection (inner_boundary, contentType, av);
969 switch (av.TransferEncoding) {
970 case TransferEncoding.Base64:
971 byte [] content = new byte [av.ContentStream.Length];
972 av.ContentStream.Read (content, 0, content.Length);
973 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
975 case TransferEncoding.QuotedPrintable:
976 byte [] bytes = new byte [av.ContentStream.Length];
977 av.ContentStream.Read (bytes, 0, bytes.Length);
978 SendData (ToQuotedPrintable (bytes));
980 case TransferEncoding.SevenBit:
981 case TransferEncoding.Unknown:
982 content = new byte [av.ContentStream.Length];
983 av.ContentStream.Read (content, 0, content.Length);
984 SendData (Encoding.ASCII.GetString (content));
988 if (av.LinkedResources.Count > 0) {
989 SendLinkedResources (message, av.LinkedResources, alt_boundary);
990 EndSection (alt_boundary);
993 if (!attachmentExists)
994 SendData (string.Empty);
999 alternateViews.Remove (body);
1001 EndSection (inner_boundary);
1004 private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
1006 foreach (LinkedResource lr in resources) {
1007 StartSection (boundary, lr.ContentType, lr);
1009 switch (lr.TransferEncoding) {
1010 case TransferEncoding.Base64:
1011 byte [] content = new byte [lr.ContentStream.Length];
1012 lr.ContentStream.Read (content, 0, content.Length);
1013 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1015 case TransferEncoding.QuotedPrintable:
1016 byte [] bytes = new byte [lr.ContentStream.Length];
1017 lr.ContentStream.Read (bytes, 0, bytes.Length);
1018 SendData (ToQuotedPrintable (bytes));
1020 case TransferEncoding.SevenBit:
1021 case TransferEncoding.Unknown:
1022 content = new byte [lr.ContentStream.Length];
1023 lr.ContentStream.Read (content, 0, content.Length);
1024 SendData (Encoding.ASCII.GetString (content));
1030 private void SendAttachments (MailMessage message, Attachment body, string boundary) {
1031 foreach (Attachment att in message.Attachments) {
1032 ContentType contentType = new ContentType (att.ContentType.ToString ());
1033 if (att.Name != null) {
1034 contentType.Name = att.Name;
1035 if (att.NameEncoding != null)
1036 contentType.CharSet = att.NameEncoding.HeaderName;
1037 att.ContentDisposition.FileName = att.Name;
1039 StartSection (boundary, contentType, att, att != body);
1041 byte [] content = new byte [att.ContentStream.Length];
1042 att.ContentStream.Read (content, 0, content.Length);
1043 switch (att.TransferEncoding) {
1044 case TransferEncoding.Base64:
1045 SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
1047 case TransferEncoding.QuotedPrintable:
1048 SendData (ToQuotedPrintable (content));
1050 case TransferEncoding.SevenBit:
1051 case TransferEncoding.Unknown:
1052 SendData (Encoding.ASCII.GetString (content));
1056 SendData (string.Empty);
1060 private SmtpResponse SendCommand (string command)
1062 writer.Write (command);
1063 // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
1064 writer.Write ("\r\n");
1069 private void SendHeader (string name, string value)
1071 SendData (String.Format ("{0}: {1}", name, value));
1074 private void StartSection (string section, ContentType sectionContentType)
1076 SendData (String.Format ("--{0}", section));
1077 SendHeader ("content-type", sectionContentType.ToString ());
1078 SendData (string.Empty);
1081 private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
1083 SendData (String.Format ("--{0}", section));
1084 SendHeader ("content-type", sectionContentType.ToString ());
1085 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1086 if (!string.IsNullOrEmpty (att.ContentId))
1087 SendHeader("content-ID", "<" + att.ContentId + ">");
1088 SendData (string.Empty);
1091 private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
1092 SendData (String.Format ("--{0}", section));
1093 if (!string.IsNullOrEmpty (att.ContentId))
1094 SendHeader("content-ID", "<" + att.ContentId + ">");
1095 SendHeader ("content-type", sectionContentType.ToString ());
1096 SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
1097 if (sendDisposition)
1098 SendHeader ("content-disposition", att.ContentDisposition.ToString ());
1099 SendData (string.Empty);
1102 // use proper encoding to escape input
1103 private string ToQuotedPrintable (string input, Encoding enc)
1105 byte [] bytes = enc.GetBytes (input);
1106 return ToQuotedPrintable (bytes);
1109 private string ToQuotedPrintable (byte [] bytes)
1111 StringWriter writer = new StringWriter ();
1112 int charsInLine = 0;
1114 StringBuilder sb = new StringBuilder("=", 3);
1115 byte equalSign = (byte)'=';
1118 foreach (byte i in bytes) {
1119 if (i > 127 || i == equalSign) {
1121 sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
1124 c = Convert.ToChar (i);
1125 if (c == '\r' || c == '\n') {
1133 charsInLine += curLen;
1134 if (charsInLine > 75) {
1135 writer.Write ("=\r\n");
1136 charsInLine = curLen;
1141 writer.Write (sb.ToString ());
1144 return writer.ToString ();
1146 private static string GetTransferEncodingName (TransferEncoding encoding)
1149 case TransferEncoding.QuotedPrintable:
1150 return "quoted-printable";
1151 case TransferEncoding.SevenBit:
1153 case TransferEncoding.Base64:
1159 private void InitiateSecureConnection () {
1160 SmtpResponse response = SendCommand ("STARTTLS");
1162 if (IsError (response)) {
1163 throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
1167 var tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
1168 var settings = MSI.MonoTlsSettings.CopyDefaultSettings ();
1169 settings.UseServicePointManagerCallback = true;
1170 var sslStream = tlsProvider.CreateSslStream (stream, false, settings);
1171 CheckCancellation ();
1172 sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1173 stream = sslStream.AuthenticatedStream;
1176 throw new SystemException ("You are using an incomplete System.dll build");
1180 void Authenticate ()
1182 string user = null, pass = null;
1184 if (UseDefaultCredentials) {
1185 user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
1186 pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
1187 } else if (Credentials != null) {
1188 user = Credentials.GetCredential (host, port, "smtp").UserName;
1189 pass = Credentials.GetCredential (host, port, "smtp").Password;
1194 Authenticate (user, pass);
1197 void CheckStatus (SmtpResponse status, int i)
1199 if (((int) status.StatusCode) != i)
1200 throw new SmtpException (status.StatusCode, status.Description);
1203 void ThrowIfError (SmtpResponse status)
1205 if (IsError (status))
1206 throw new SmtpException (status.StatusCode, status.Description);
1209 void Authenticate (string user, string password)
1211 if (authMechs == AuthMechs.None)
1214 SmtpResponse status;
1216 if ((authMechs & AuthMechs.DigestMD5) != 0) {
1217 status = SendCommand ("AUTH DIGEST-MD5");
1218 CheckStatus (status, 334);
1219 string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
1220 Console.WriteLine ("CHALLENGE: {0}", challenge);
1221 DigestSession session = new DigestSession ();
1222 session.Parse (false, challenge);
1223 string response = session.Authenticate (this, user, password);
1224 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
1225 CheckStatus (status, 235);
1227 if ((authMechs & AuthMechs.Login) != 0) {
1228 status = SendCommand ("AUTH LOGIN");
1229 CheckStatus (status, 334);
1230 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
1231 CheckStatus (status, 334);
1232 status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
1233 CheckStatus (status, 235);
1234 } else if ((authMechs & AuthMechs.Plain) != 0) {
1235 string s = String.Format ("\0{0}\0{1}", user, password);
1236 s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
1237 status = SendCommand ("AUTH PLAIN " + s);
1238 CheckStatus (status, 235);
1240 throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
1244 #endregion // Methods
1246 // The HeaderName struct is used to store constant string values representing mail headers.
1247 private struct HeaderName {
1248 public const string ContentTransferEncoding = "Content-Transfer-Encoding";
1249 public const string ContentType = "Content-Type";
1250 public const string Bcc = "Bcc";
1251 public const string Cc = "Cc";
1252 public const string From = "From";
1253 public const string Subject = "Subject";
1254 public const string To = "To";
1255 public const string MimeVersion = "MIME-Version";
1256 public const string MessageId = "Message-ID";
1257 public const string Priority = "Priority";
1258 public const string Importance = "Importance";
1259 public const string XPriority = "X-Priority";
1260 public const string Date = "Date";
1263 // This object encapsulates the status code and description of an SMTP response.
1264 private struct SmtpResponse {
1265 public SmtpStatusCode StatusCode;
1266 public string Description;
1268 public static SmtpResponse Parse (string line) {
1269 SmtpResponse response = new SmtpResponse ();
1271 if (line.Length < 4)
1272 throw new SmtpException ("Response is to short " +
1275 if ((line [3] != ' ') && (line [3] != '-'))
1276 throw new SmtpException ("Response format is wrong.(" +
1279 // parse the response code
1280 response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
1282 // set the raw response
1283 response.Description = line;
1290 class CCredentialsByHost : ICredentialsByHost
1292 public CCredentialsByHost (string userName, string password) {
1293 this.userName = userName;
1294 this.password = password;
1297 public NetworkCredential GetCredential (string host, int port, string authenticationType) {
1298 return new NetworkCredential (userName, password);
1301 private string userName;
1302 private string password;