SmtpClient.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. //
  2. // System.Net.Mail.SmtpClient.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2004
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_2_0
  30. using System;
  31. using System.Collections.Generic;
  32. using System.ComponentModel;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Mime;
  36. using System.Net.Sockets;
  37. using System.Security.Cryptography.X509Certificates;
  38. using System.Text;
  39. using System.Threading;
  40. using System.Reflection;
  41. using System.Net.Configuration;
  42. using System.Configuration;
  43. namespace System.Net.Mail {
  44. public class SmtpClient
  45. {
  46. #region Fields
  47. string host;
  48. int port;
  49. int timeout = 100000;
  50. ICredentialsByHost credentials;
  51. bool useDefaultCredentials = false;
  52. string pickupDirectoryLocation;
  53. SmtpDeliveryMethod deliveryMethod;
  54. bool enableSsl;
  55. X509CertificateCollection clientCertificates;
  56. TcpClient client;
  57. NetworkStream stream;
  58. StreamWriter writer;
  59. StreamReader reader;
  60. int boundaryIndex;
  61. MailAddress defaultFrom;
  62. Mutex mutex = new Mutex ();
  63. const string MimeVersion = "1.0 (produced by Mono System.Net.Mail.SmtpClient)";
  64. #endregion // Fields
  65. #region Constructors
  66. public SmtpClient ()
  67. : this (null, 0)
  68. {
  69. }
  70. public SmtpClient (string host)
  71. : this (host, 0)
  72. {
  73. }
  74. public SmtpClient (string host, int port) {
  75. #if CONFIGURATION_DEP
  76. SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
  77. if (cfg != null) {
  78. this.host = cfg.Network.Host;
  79. this.port = cfg.Network.Port;
  80. if (cfg.Network.UserName != null) {
  81. string password = String.Empty;
  82. if (cfg.Network.Password != null)
  83. password = cfg.Network.Password;
  84. Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
  85. }
  86. if (cfg.From != null)
  87. defaultFrom = new MailAddress (cfg.From);
  88. }
  89. #endif
  90. if (!String.IsNullOrEmpty (host))
  91. this.host = host;
  92. if (port != 0)
  93. this.port = port;
  94. }
  95. #endregion // Constructors
  96. #region Properties
  97. [MonoTODO("Client certificates are not supported")]
  98. public X509CertificateCollection ClientCertificates {
  99. get {
  100. throw new NotImplementedException ("Client certificates are not supported");
  101. return clientCertificates;
  102. }
  103. }
  104. public ICredentialsByHost Credentials {
  105. get { return credentials; }
  106. set { credentials = value; }
  107. }
  108. public SmtpDeliveryMethod DeliveryMethod {
  109. get { return deliveryMethod; }
  110. set { deliveryMethod = value; }
  111. }
  112. public bool EnableSsl {
  113. get { return enableSsl; }
  114. set { enableSsl = value; }
  115. }
  116. public string Host {
  117. get { return host; }
  118. // FIXME: Check to make sure an email is not being sent.
  119. set {
  120. if (value == null)
  121. throw new ArgumentNullException ();
  122. if (value.Length == 0)
  123. throw new ArgumentException ();
  124. host = value;
  125. }
  126. }
  127. public string PickupDirectoryLocation {
  128. get { return pickupDirectoryLocation; }
  129. set { pickupDirectoryLocation = value; }
  130. }
  131. public int Port {
  132. get { return port; }
  133. // FIXME: Check to make sure an email is not being sent.
  134. set {
  135. if (value <= 0)
  136. throw new ArgumentOutOfRangeException ();
  137. port = value;
  138. }
  139. }
  140. public ServicePoint ServicePoint {
  141. get { throw new NotImplementedException (); }
  142. }
  143. public int Timeout {
  144. get { return timeout; }
  145. // FIXME: Check to make sure an email is not being sent.
  146. set {
  147. if (value < 0)
  148. throw new ArgumentOutOfRangeException ();
  149. timeout = value;
  150. }
  151. }
  152. public bool UseDefaultCredentials {
  153. get { return useDefaultCredentials; }
  154. set { throw new NotImplementedException ("Default credentials are not supported"); }
  155. }
  156. #endregion // Properties
  157. #region Events
  158. public event SendCompletedEventHandler SendCompleted;
  159. #endregion // Events
  160. #region Methods
  161. private void EndSection (string section)
  162. {
  163. SendData (String.Format ("--{0}--", section));
  164. SendData (string.Empty);
  165. }
  166. private string GenerateBoundary ()
  167. {
  168. string output = GenerateBoundary (boundaryIndex);
  169. boundaryIndex += 1;
  170. return output;
  171. }
  172. private static string GenerateBoundary (int index)
  173. {
  174. return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
  175. }
  176. private bool IsError (SmtpResponse status)
  177. {
  178. return ((int) status.StatusCode) >= 400;
  179. }
  180. protected void OnSendCompleted (AsyncCompletedEventArgs e)
  181. {
  182. if (SendCompleted != null)
  183. SendCompleted (this, e);
  184. }
  185. private SmtpResponse Read () {
  186. byte [] buffer = new byte [512];
  187. int position = 0;
  188. bool lastLine = false;
  189. do {
  190. int readLength = stream.Read (buffer, position, buffer.Length - position);
  191. if (readLength > 0) {
  192. int available = position + readLength - 1;
  193. if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
  194. for (int index = available - 3; ; index--) {
  195. if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
  196. lastLine = buffer [index + 4] == ' ';
  197. break;
  198. }
  199. }
  200. // move position
  201. position += readLength;
  202. // check if buffer is full
  203. if (position == buffer.Length) {
  204. byte [] newBuffer = new byte [buffer.Length * 2];
  205. Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
  206. buffer = newBuffer;
  207. }
  208. }
  209. else {
  210. break;
  211. }
  212. } while (!lastLine);
  213. if (position > 0) {
  214. Encoding encoding = new ASCIIEncoding ();
  215. string line = encoding.GetString (buffer, 0, position - 1);
  216. // parse the line to the lastResponse object
  217. SmtpResponse response = SmtpResponse.Parse (line);
  218. return response;
  219. }
  220. else {
  221. throw new System.IO.IOException ("Connection closed");
  222. }
  223. }
  224. public void Send (MailMessage message) {
  225. CheckHostAndPort ();
  226. // Block while sending
  227. mutex.WaitOne ();
  228. SmtpResponse status;
  229. client = new TcpClient (host, port);
  230. stream = client.GetStream ();
  231. writer = new StreamWriter (stream);
  232. reader = new StreamReader (stream);
  233. status = Read ();
  234. if (IsError (status))
  235. throw new SmtpException (status.StatusCode, status.Description);
  236. // EHLO
  237. status = SendCommand (Command.Ehlo, Dns.GetHostName ());
  238. if (IsError (status)) {
  239. throw new SmtpException (status.StatusCode, status.Description);
  240. }
  241. if (EnableSsl) {
  242. InitiateSecureConnection ();
  243. }
  244. PerformAuthentication ();
  245. MailAddress from = message.From;
  246. if (from == null)
  247. from = defaultFrom;
  248. // MAIL FROM:
  249. status = SendCommand (Command.MailFrom, '<' + from.Address + '>');
  250. if (IsError (status)) {
  251. throw new SmtpException (status.StatusCode, status.Description);
  252. }
  253. // Send RCPT TO: for all recipients
  254. List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
  255. for (int i = 0; i < message.To.Count; i ++) {
  256. status = SendCommand (Command.RcptTo, '<' + message.To [i].Address + '>');
  257. if (IsError (status))
  258. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
  259. }
  260. for (int i = 0; i < message.CC.Count; i ++) {
  261. status = SendCommand (Command.RcptTo, '<' + message.CC [i].Address + '>');
  262. if (IsError (status))
  263. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
  264. }
  265. for (int i = 0; i < message.Bcc.Count; i ++) {
  266. status = SendCommand (Command.RcptTo, '<' + message.Bcc [i].Address + '>');
  267. if (IsError (status))
  268. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
  269. }
  270. #if TARGET_JVM // List<T>.ToArray () is not supported
  271. if (sfre.Count > 0) {
  272. SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
  273. sfre.CopyTo (xs);
  274. throw new SmtpFailedRecipientsException ("failed recipients", xs);
  275. }
  276. #else
  277. if (sfre.Count >0)
  278. throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
  279. #endif
  280. // DATA
  281. status = SendCommand (Command.Data);
  282. if (IsError (status))
  283. throw new SmtpException (status.StatusCode, status.Description);
  284. // Send message headers
  285. SendHeader (HeaderName.From, from.ToString ());
  286. SendHeader (HeaderName.To, message.To.ToString ());
  287. if (message.CC.Count > 0)
  288. SendHeader (HeaderName.Cc, message.CC.ToString ());
  289. if (message.Bcc.Count > 0)
  290. SendHeader (HeaderName.Bcc, message.Bcc.ToString ());
  291. SendHeader (HeaderName.Subject, message.Subject);
  292. foreach (string s in message.Headers.AllKeys)
  293. SendHeader (s, message.Headers [s]);
  294. AddPriorityHeader (message);
  295. bool hasAlternateViews = (message.AlternateViews.Count > 0);
  296. bool hasAttachments = (message.Attachments.Count > 0);
  297. if (hasAttachments || hasAlternateViews) {
  298. SendMultipartBody (message);
  299. }
  300. else {
  301. SendSimpleBody (message);
  302. }
  303. SendData (".");
  304. status = Read ();
  305. if (IsError (status))
  306. throw new SmtpException (status.StatusCode, status.Description);
  307. try {
  308. status = SendCommand (Command.Quit);
  309. }
  310. catch (System.IO.IOException) {
  311. //We excuse server for the rude connection closing as a response to QUIT
  312. }
  313. writer.Close ();
  314. reader.Close ();
  315. stream.Close ();
  316. client.Close ();
  317. // Release the mutex to allow other threads access
  318. mutex.ReleaseMutex ();
  319. }
  320. public void Send (string from, string to, string subject, string body)
  321. {
  322. Send (new MailMessage (from, to, subject, body));
  323. }
  324. private void SendData (string data)
  325. {
  326. writer.WriteLine (data);
  327. writer.Flush ();
  328. }
  329. public void SendAsync (MailMessage message, object userToken)
  330. {
  331. Send (message);
  332. OnSendCompleted (new AsyncCompletedEventArgs (null, false, userToken));
  333. }
  334. public void SendAsync (string from, string to, string subject, string body, object userToken)
  335. {
  336. SendAsync (new MailMessage (from, to, subject, body), userToken);
  337. }
  338. public void SendAsyncCancel ()
  339. {
  340. throw new NotImplementedException ();
  341. }
  342. private void AddPriorityHeader (MailMessage message) {
  343. switch (message.Priority) {
  344. case MailPriority.High:
  345. SendHeader (HeaderName.Priority, "Urgent");
  346. SendHeader (HeaderName.Importance, "high");
  347. SendHeader (HeaderName.XPriority, "1");
  348. break;
  349. case MailPriority.Low:
  350. SendHeader (HeaderName.Priority, "Non-Urgent");
  351. SendHeader (HeaderName.Importance, "low");
  352. SendHeader (HeaderName.XPriority, "5");
  353. break;
  354. }
  355. }
  356. private void SendSimpleBody (MailMessage message) {
  357. SendHeader ("Content-Type", message.BodyContentType.ToString ());
  358. SendData (string.Empty);
  359. SendData (message.Body);
  360. }
  361. private void SendMultipartBody (MailMessage message) {
  362. boundaryIndex = 0;
  363. string boundary = GenerateBoundary ();
  364. // Figure out the message content type
  365. ContentType messageContentType = message.BodyContentType;
  366. messageContentType.Boundary = boundary;
  367. messageContentType.MediaType = "multipart/mixed";
  368. SendHeader ("Content-Type", messageContentType.ToString ());
  369. SendData (string.Empty);
  370. SendData (message.Body);
  371. SendData (string.Empty);
  372. message.AlternateViews.Add (AlternateView.CreateAlternateViewFromString (message.Body, new ContentType ("text/plain")));
  373. if (message.AlternateViews.Count > 0) {
  374. SendAlternateViews (message, boundary);
  375. }
  376. if (message.Attachments.Count > 0) {
  377. SendAttachments (message, boundary);
  378. }
  379. EndSection (boundary);
  380. }
  381. private void SendAlternateViews (MailMessage message, string boundary) {
  382. AlternateViewCollection alternateViews = message.AlternateViews;
  383. string inner_boundary = GenerateBoundary ();
  384. ContentType messageContentType = message.BodyContentType;
  385. messageContentType.Boundary = inner_boundary;
  386. messageContentType.MediaType = "multipart/alternative";
  387. StartSection (boundary, messageContentType);
  388. for (int i = 0; i < alternateViews.Count; i += 1) {
  389. ContentType contentType = new ContentType (alternateViews [i].ContentType.ToString ());
  390. StartSection (inner_boundary, contentType, alternateViews [i].TransferEncoding);
  391. switch (alternateViews [i].TransferEncoding) {
  392. case TransferEncoding.Base64:
  393. byte [] content = new byte [alternateViews [i].ContentStream.Length];
  394. alternateViews [i].ContentStream.Read (content, 0, content.Length);
  395. #if TARGET_JVM
  396. SendData (Convert.ToBase64String (content));
  397. #else
  398. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  399. #endif
  400. break;
  401. case TransferEncoding.QuotedPrintable:
  402. StreamReader sr = new StreamReader (alternateViews [i].ContentStream);
  403. SendData (ToQuotedPrintable (sr.ReadToEnd ()));
  404. break;
  405. //case TransferEncoding.SevenBit:
  406. //case TransferEncoding.Unknown:
  407. default:
  408. SendData ("TO BE IMPLEMENTED");
  409. break;
  410. }
  411. SendData (string.Empty);
  412. }
  413. EndSection (inner_boundary);
  414. }
  415. private void SendAttachments (MailMessage message, string boundary) {
  416. AttachmentCollection attachments = message.Attachments;
  417. for (int i = 0; i < attachments.Count; i += 1) {
  418. ContentType contentType = new ContentType (attachments [i].ContentType.ToString ());
  419. attachments [i].ContentDisposition.FileName = attachments [i].Name;
  420. StartSection (boundary, contentType, attachments [i].TransferEncoding, attachments [i].ContentDisposition);
  421. switch (attachments [i].TransferEncoding) {
  422. case TransferEncoding.Base64:
  423. byte[] content = new byte [attachments [i].ContentStream.Length];
  424. attachments [i].ContentStream.Read (content, 0, content.Length);
  425. #if TARGET_JVM
  426. SendData (Convert.ToBase64String (content));
  427. #else
  428. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  429. #endif
  430. break;
  431. case TransferEncoding.QuotedPrintable:
  432. StreamReader sr = new StreamReader (attachments [i].ContentStream);
  433. SendData (ToQuotedPrintable (sr.ReadToEnd ()));
  434. break;
  435. //case TransferEncoding.SevenBit:
  436. //case TransferEncoding.Unknown:
  437. default:
  438. SendData ("TO BE IMPLEMENTED");
  439. break;
  440. }
  441. SendData (string.Empty);
  442. }
  443. }
  444. private SmtpResponse SendCommand (string command, string data)
  445. {
  446. writer.Write (command);
  447. writer.Write (" ");
  448. SendData (data);
  449. return Read ();
  450. }
  451. private SmtpResponse SendCommand (string command)
  452. {
  453. writer.WriteLine (command);
  454. writer.Flush ();
  455. return Read ();
  456. }
  457. private void SendHeader (string name, string value)
  458. {
  459. SendData (String.Format ("{0}: {1}", name, value));
  460. }
  461. private void StartSection (string section, ContentType sectionContentType)
  462. {
  463. SendData (string.Empty);
  464. SendData (String.Format ("--{0}", section));
  465. SendHeader ("content-type", sectionContentType.ToString ());
  466. SendData (string.Empty);
  467. }
  468. private void StartSection (string section, ContentType sectionContentType,TransferEncoding transferEncoding)
  469. {
  470. SendData (String.Format ("--{0}", section));
  471. SendHeader ("content-type", sectionContentType.ToString ());
  472. SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
  473. SendData (string.Empty);
  474. }
  475. private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) {
  476. SendData (String.Format ("--{0}", section));
  477. SendHeader ("content-type", sectionContentType.ToString ());
  478. SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
  479. SendHeader ("content-disposition", contentDisposition.ToString ());
  480. SendData (string.Empty);
  481. }
  482. private string ToQuotedPrintable (string input) {
  483. StringReader reader = new StringReader (input);
  484. StringWriter writer = new StringWriter ();
  485. int i;
  486. while ((i = reader.Read ()) > 0) {
  487. if (i > 127) {
  488. writer.Write ("=");
  489. writer.Write (Convert.ToString (i, 16).ToUpper ());
  490. }
  491. else
  492. writer.Write (Convert.ToChar (i));
  493. }
  494. return writer.GetStringBuilder ().ToString ();
  495. }
  496. private static string GetTransferEncodingName (TransferEncoding encoding)
  497. {
  498. switch (encoding) {
  499. case TransferEncoding.QuotedPrintable:
  500. return "quoted-printable";
  501. case TransferEncoding.SevenBit:
  502. return "7bit";
  503. case TransferEncoding.Base64:
  504. return "base64";
  505. }
  506. return "unknown";
  507. }
  508. private void InitiateSecureConnection () {
  509. SmtpResponse response = SendCommand (Command.StartTls);
  510. if (IsError (response)) {
  511. throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
  512. }
  513. ChangeToSSLSocket ();
  514. }
  515. private bool ChangeToSSLSocket () {
  516. #if TARGET_JVM
  517. stream.ChangeToSSLSocket ();
  518. return true;
  519. #else
  520. throw new NotImplementedException ();
  521. #endif
  522. }
  523. void CheckHostAndPort () {
  524. if (String.IsNullOrEmpty (Host))
  525. throw new InvalidOperationException ("The SMTP host was not specified");
  526. if (Port == 0)
  527. Port = 25;
  528. }
  529. void PerformAuthentication () {
  530. if (UseDefaultCredentials) {
  531. Authenticate (
  532. CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName,
  533. CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password);
  534. }
  535. else if (Credentials != null) {
  536. Authenticate (
  537. Credentials.GetCredential (host, port, "smtp").UserName,
  538. Credentials.GetCredential (host, port, "smtp").Password);
  539. }
  540. }
  541. void Authenticate (string Username, string Password) {
  542. SmtpResponse status = SendCommand (Command.AuthLogin);
  543. if (((int) status.StatusCode) != 334) {
  544. throw new SmtpException (status.StatusCode, status.Description);
  545. }
  546. status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Username)));
  547. if (((int) status.StatusCode) != 334) {
  548. throw new SmtpException (status.StatusCode, status.Description);
  549. }
  550. status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Password)));
  551. if (IsError (status)) {
  552. throw new SmtpException (status.StatusCode, status.Description);
  553. }
  554. }
  555. /*
  556. [MonoTODO]
  557. private sealed ContextAwareResult IGetContextAwareResult.GetContextAwareResult ()
  558. {
  559. throw new NotImplementedException ();
  560. }
  561. */
  562. #endregion // Methods
  563. // The Command struct is used to store constant string values representing SMTP commands.
  564. private struct Command {
  565. public const string Data = "DATA";
  566. public const string Helo = "HELO";
  567. public const string Ehlo = "EHLO";
  568. public const string MailFrom = "MAIL FROM:";
  569. public const string Quit = "QUIT";
  570. public const string RcptTo = "RCPT TO:";
  571. public const string StartTls = "STARTTLS";
  572. public const string AuthLogin = "AUTH LOGIN";
  573. }
  574. // The HeaderName struct is used to store constant string values representing mail headers.
  575. private struct HeaderName {
  576. public const string ContentTransferEncoding = "Content-Transfer-Encoding";
  577. public const string ContentType = "Content-Type";
  578. public const string Bcc = "Bcc";
  579. public const string Cc = "Cc";
  580. public const string From = "From";
  581. public const string Subject = "Subject";
  582. public const string To = "To";
  583. public const string MimeVersion = "MIME-Version";
  584. public const string MessageId = "Message-ID";
  585. public const string Priority = "Priority";
  586. public const string Importance = "Importance";
  587. public const string XPriority = "X-Priority";
  588. }
  589. // This object encapsulates the status code and description of an SMTP response.
  590. private struct SmtpResponse {
  591. public SmtpStatusCode StatusCode;
  592. public string Description;
  593. public static SmtpResponse Parse (string line) {
  594. SmtpResponse response = new SmtpResponse ();
  595. if (line.Length < 4)
  596. throw new SmtpException ("Response is to short " +
  597. line.Length + ".");
  598. if ((line [3] != ' ') && (line [3] != '-'))
  599. throw new SmtpException ("Response format is wrong.(" +
  600. line + ")");
  601. // parse the response code
  602. response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
  603. // set the rawsponse
  604. response.Description = line;
  605. return response;
  606. }
  607. }
  608. }
  609. class CCredentialsByHost : ICredentialsByHost
  610. {
  611. public CCredentialsByHost (string userName, string password) {
  612. this.userName = userName;
  613. this.password = password;
  614. }
  615. public NetworkCredential GetCredential (string host, int port, string authenticationType) {
  616. return new NetworkCredential (userName, password);
  617. }
  618. private string userName;
  619. private string password;
  620. }
  621. }
  622. #endif // NET_2_0