SmtpClient.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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.Globalization;
  34. using System.IO;
  35. using System.Net;
  36. using System.Net.Mime;
  37. using System.Net.Sockets;
  38. using System.Security.Cryptography.X509Certificates;
  39. using System.Text;
  40. using System.Threading;
  41. using System.Reflection;
  42. using System.Net.Configuration;
  43. using System.Configuration;
  44. namespace System.Net.Mail {
  45. public class SmtpClient
  46. {
  47. #region Fields
  48. string host;
  49. int port;
  50. int timeout = 100000;
  51. ICredentialsByHost credentials;
  52. bool useDefaultCredentials = false;
  53. string pickupDirectoryLocation;
  54. SmtpDeliveryMethod deliveryMethod;
  55. bool enableSsl;
  56. //X509CertificateCollection clientCertificates;
  57. TcpClient client;
  58. NetworkStream stream;
  59. StreamWriter writer;
  60. StreamReader reader;
  61. int boundaryIndex;
  62. MailAddress defaultFrom;
  63. MailMessage messageInProcess;
  64. // ESMTP state
  65. enum AuthMechs {
  66. None = 0,
  67. CramMD5 = 0x01,
  68. DigestMD5 = 0x02,
  69. GssAPI = 0x04,
  70. Kerberos4 = 0x08,
  71. Login = 0x10,
  72. Plain = 0x20,
  73. }
  74. AuthMechs authMechs = AuthMechs.None;
  75. bool canStartTLS = false;
  76. Mutex mutex = new Mutex ();
  77. #endregion // Fields
  78. #region Constructors
  79. public SmtpClient ()
  80. : this (null, 0)
  81. {
  82. }
  83. public SmtpClient (string host)
  84. : this (host, 0)
  85. {
  86. }
  87. public SmtpClient (string host, int port) {
  88. #if CONFIGURATION_DEP
  89. SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
  90. if (cfg != null) {
  91. this.host = cfg.Network.Host;
  92. this.port = cfg.Network.Port;
  93. if (cfg.Network.UserName != null) {
  94. string password = String.Empty;
  95. if (cfg.Network.Password != null)
  96. password = cfg.Network.Password;
  97. Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
  98. }
  99. if (cfg.From != null)
  100. defaultFrom = new MailAddress (cfg.From);
  101. }
  102. #endif
  103. if (!String.IsNullOrEmpty (host))
  104. this.host = host;
  105. if (port != 0)
  106. this.port = port;
  107. }
  108. #endregion // Constructors
  109. #region Properties
  110. [MonoTODO("Client certificates are not supported")]
  111. public X509CertificateCollection ClientCertificates {
  112. get {
  113. throw new NotImplementedException ("Client certificates are not supported");
  114. //return clientCertificates;
  115. }
  116. }
  117. public ICredentialsByHost Credentials {
  118. get { return credentials; }
  119. set { credentials = value; }
  120. }
  121. public SmtpDeliveryMethod DeliveryMethod {
  122. get { return deliveryMethod; }
  123. set { deliveryMethod = value; }
  124. }
  125. public bool EnableSsl {
  126. // FIXME: So... is this supposed to enable SSL port functionality? or STARTTLS? Or both?
  127. get { return enableSsl; }
  128. set { enableSsl = value; }
  129. }
  130. public string Host {
  131. get { return host; }
  132. // FIXME: Check to make sure an email is not being sent.
  133. set {
  134. if (value == null)
  135. throw new ArgumentNullException ();
  136. if (value.Length == 0)
  137. throw new ArgumentException ();
  138. host = value;
  139. }
  140. }
  141. public string PickupDirectoryLocation {
  142. get { return pickupDirectoryLocation; }
  143. set { pickupDirectoryLocation = value; }
  144. }
  145. public int Port {
  146. get { return port; }
  147. // FIXME: Check to make sure an email is not being sent.
  148. set {
  149. if (value <= 0 || value > 65535)
  150. throw new ArgumentOutOfRangeException ();
  151. port = value;
  152. }
  153. }
  154. public ServicePoint ServicePoint {
  155. get { throw new NotImplementedException (); }
  156. }
  157. public int Timeout {
  158. get { return timeout; }
  159. set {
  160. if (value < 0)
  161. throw new ArgumentOutOfRangeException ();
  162. if (messageInProcess != null)
  163. throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
  164. timeout = value;
  165. }
  166. }
  167. public bool UseDefaultCredentials {
  168. get { return useDefaultCredentials; }
  169. [MonoNotSupported ("no DefaultCredential support in Mono")]
  170. set {
  171. if (value)
  172. throw new NotImplementedException ("Default credentials are not supported");
  173. }
  174. }
  175. #endregion // Properties
  176. #region Events
  177. public event SendCompletedEventHandler SendCompleted;
  178. #endregion // Events
  179. #region Methods
  180. private string EncodeSubjectRFC2047 (MailMessage message)
  181. {
  182. if (message.SubjectEncoding == null || Encoding.ASCII.Equals (message.SubjectEncoding))
  183. return message.Subject;
  184. string b64 = Convert.ToBase64String (message.SubjectEncoding.GetBytes (message.Subject));
  185. return String.Concat ("=?", message.SubjectEncoding.HeaderName, "?B?", b64, "?=");
  186. }
  187. private string EncodeBody (MailMessage message)
  188. {
  189. string body = message.Body;
  190. // RFC 2045 encoding
  191. switch (message.ContentTransferEncoding) {
  192. case TransferEncoding.SevenBit:
  193. return body;
  194. case TransferEncoding.Base64:
  195. return Convert.ToBase64String (message.BodyEncoding.GetBytes (body));
  196. default:
  197. return ToQuotedPrintable (body, message.BodyEncoding);
  198. }
  199. }
  200. private void EndSection (string section)
  201. {
  202. SendData (String.Format ("--{0}--", section));
  203. SendData (string.Empty);
  204. }
  205. private string GenerateBoundary ()
  206. {
  207. string output = GenerateBoundary (boundaryIndex);
  208. boundaryIndex += 1;
  209. return output;
  210. }
  211. private static string GenerateBoundary (int index)
  212. {
  213. return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
  214. }
  215. private bool IsError (SmtpResponse status)
  216. {
  217. return ((int) status.StatusCode) >= 400;
  218. }
  219. protected void OnSendCompleted (AsyncCompletedEventArgs e)
  220. {
  221. if (SendCompleted != null)
  222. SendCompleted (this, e);
  223. }
  224. private SmtpResponse Read () {
  225. byte [] buffer = new byte [512];
  226. int position = 0;
  227. bool lastLine = false;
  228. do {
  229. int readLength = stream.Read (buffer, position, buffer.Length - position);
  230. if (readLength > 0) {
  231. int available = position + readLength - 1;
  232. if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
  233. for (int index = available - 3; ; index--) {
  234. if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
  235. lastLine = buffer [index + 4] == ' ';
  236. break;
  237. }
  238. }
  239. // move position
  240. position += readLength;
  241. // check if buffer is full
  242. if (position == buffer.Length) {
  243. byte [] newBuffer = new byte [buffer.Length * 2];
  244. Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
  245. buffer = newBuffer;
  246. }
  247. }
  248. else {
  249. break;
  250. }
  251. } while (!lastLine);
  252. if (position > 0) {
  253. Encoding encoding = new ASCIIEncoding ();
  254. string line = encoding.GetString (buffer, 0, position - 1);
  255. // parse the line to the lastResponse object
  256. SmtpResponse response = SmtpResponse.Parse (line);
  257. return response;
  258. } else {
  259. throw new System.IO.IOException ("Connection closed");
  260. }
  261. }
  262. void ParseExtensions (string extens)
  263. {
  264. char []delims = new char [1] { ' ' };
  265. int ln = 0;
  266. do {
  267. if (ln != 0)
  268. ln++;
  269. if (ln > extens.Length)
  270. break;
  271. if (extens.Substring (ln, 4) == "AUTH" &&
  272. (extens[ln + 4] == ' ' || extens[ln + 4] == '=')) {
  273. int eoln = extens.IndexOf ('\n', ln + 4);
  274. string mechlist = extens.Substring (ln, eoln);
  275. string []mechs = mechlist.Split (delims);
  276. ln = eoln;
  277. for (int i = 0; i < mechs.Length; i++) {
  278. switch (mechs[i]) {
  279. case "CRAM-MD5":
  280. authMechs |= AuthMechs.CramMD5;
  281. break;
  282. case "DIGEST-MD5":
  283. authMechs |= AuthMechs.DigestMD5;
  284. break;
  285. case "GSSAPI":
  286. authMechs |= AuthMechs.GssAPI;
  287. break;
  288. case "KERBEROS_V4":
  289. authMechs |= AuthMechs.Kerberos4;
  290. break;
  291. case "LOGIN":
  292. authMechs |= AuthMechs.Login;
  293. break;
  294. case "PLAIN":
  295. authMechs |= AuthMechs.Plain;
  296. break;
  297. }
  298. }
  299. } else if (extens.Substring (ln, 8) == "STARTTLS") {
  300. canStartTLS = true;
  301. }
  302. } while ((ln = extens.IndexOf ('\n', ln)) != -1);
  303. }
  304. public void Send (MailMessage message)
  305. {
  306. if (message == null)
  307. throw new ArgumentNullException ("message");
  308. if (String.IsNullOrEmpty (Host))
  309. throw new InvalidOperationException ("The SMTP host was not specified");
  310. if (port == 0)
  311. port = 25;
  312. // Block while sending
  313. mutex.WaitOne ();
  314. messageInProcess = message;
  315. SmtpResponse status;
  316. client = new TcpClient (host, port);
  317. stream = client.GetStream ();
  318. writer = new StreamWriter (stream);
  319. reader = new StreamReader (stream);
  320. status = Read ();
  321. if (IsError (status))
  322. throw new SmtpException (status.StatusCode, status.Description);
  323. // EHLO
  324. // FIXME: parse the list of extensions so we don't bother wasting
  325. // our time trying commands if they aren't supported.
  326. status = SendCommand ("EHLO " + Dns.GetHostName ());
  327. if (IsError (status)) {
  328. status = SendCommand ("HELO " + Dns.GetHostName ());
  329. if (IsError (status))
  330. throw new SmtpException (status.StatusCode, status.Description);
  331. } else {
  332. // Parse ESMTP extensions
  333. string extens = status.Description;
  334. if (extens != null)
  335. ParseExtensions (extens);
  336. }
  337. if (enableSsl) {
  338. // FIXME: I get the feeling from the docs that EnableSsl is meant
  339. // for using the SSL-port and not STARTTLS (or, if it includes
  340. // STARTTLS... only use STARTTLS if the SSL-type in the certificate
  341. // is TLS and not SSLv2 or SSLv3)
  342. // FIXME: even tho we have a canStartTLS flag... ignore it for now
  343. // so that the STARTTLS command can throw the appropriate
  344. // SmtpException if STARTTLS is unavailable
  345. InitiateSecureConnection ();
  346. // FIXME: re-EHLO?
  347. }
  348. if (authMechs != AuthMechs.None)
  349. Authenticate ();
  350. MailAddress from = message.From;
  351. if (from == null)
  352. from = defaultFrom;
  353. // MAIL FROM:
  354. status = SendCommand ("MAIL FROM:<" + from.Address + '>');
  355. if (IsError (status)) {
  356. throw new SmtpException (status.StatusCode, status.Description);
  357. }
  358. // Send RCPT TO: for all recipients
  359. List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
  360. for (int i = 0; i < message.To.Count; i ++) {
  361. status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
  362. if (IsError (status))
  363. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
  364. }
  365. for (int i = 0; i < message.CC.Count; i ++) {
  366. status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
  367. if (IsError (status))
  368. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
  369. }
  370. for (int i = 0; i < message.Bcc.Count; i ++) {
  371. status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
  372. if (IsError (status))
  373. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
  374. }
  375. #if TARGET_JVM // List<T>.ToArray () is not supported
  376. if (sfre.Count > 0) {
  377. SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
  378. sfre.CopyTo (xs);
  379. throw new SmtpFailedRecipientsException ("failed recipients", xs);
  380. }
  381. #else
  382. if (sfre.Count >0)
  383. throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
  384. #endif
  385. // DATA
  386. status = SendCommand ("DATA");
  387. if (IsError (status))
  388. throw new SmtpException (status.StatusCode, status.Description);
  389. // Send message headers
  390. SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
  391. SendHeader (HeaderName.From, from.ToString ());
  392. SendHeader (HeaderName.To, message.To.ToString ());
  393. if (message.CC.Count > 0)
  394. SendHeader (HeaderName.Cc, message.CC.ToString ());
  395. SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
  396. foreach (string s in message.Headers.AllKeys)
  397. SendHeader (s, message.Headers [s]);
  398. AddPriorityHeader (message);
  399. bool hasAlternateViews = (message.AlternateViews.Count > 0);
  400. bool hasAttachments = (message.Attachments.Count > 0);
  401. if (hasAttachments || hasAlternateViews) {
  402. SendMultipartBody (message);
  403. } else {
  404. SendSimpleBody (message);
  405. }
  406. SendData (".");
  407. status = Read ();
  408. if (IsError (status))
  409. throw new SmtpException (status.StatusCode, status.Description);
  410. try {
  411. status = SendCommand ("QUIT");
  412. } catch (System.IO.IOException) {
  413. // We excuse server for the rude connection closing as a response to QUIT
  414. }
  415. writer.Close ();
  416. reader.Close ();
  417. stream.Close ();
  418. client.Close ();
  419. // Release the mutex to allow other threads access
  420. mutex.ReleaseMutex ();
  421. messageInProcess = null;
  422. }
  423. public void Send (string from, string to, string subject, string body)
  424. {
  425. Send (new MailMessage (from, to, subject, body));
  426. }
  427. private void SendData (string data)
  428. {
  429. // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
  430. writer.Write (data.Replace ("\r\n", "\n")
  431. .Replace ('\r', '\n')
  432. .Replace ("\n", "\r\n"));
  433. writer.Write ("\r\n");
  434. writer.Flush ();
  435. }
  436. public void SendAsync (MailMessage message, object userToken)
  437. {
  438. Send (message);
  439. OnSendCompleted (new AsyncCompletedEventArgs (null, false, userToken));
  440. }
  441. public void SendAsync (string from, string to, string subject, string body, object userToken)
  442. {
  443. SendAsync (new MailMessage (from, to, subject, body), userToken);
  444. }
  445. public void SendAsyncCancel ()
  446. {
  447. throw new NotImplementedException ();
  448. }
  449. private void AddPriorityHeader (MailMessage message) {
  450. switch (message.Priority) {
  451. case MailPriority.High:
  452. SendHeader (HeaderName.Priority, "Urgent");
  453. SendHeader (HeaderName.Importance, "high");
  454. SendHeader (HeaderName.XPriority, "1");
  455. break;
  456. case MailPriority.Low:
  457. SendHeader (HeaderName.Priority, "Non-Urgent");
  458. SendHeader (HeaderName.Importance, "low");
  459. SendHeader (HeaderName.XPriority, "5");
  460. break;
  461. }
  462. }
  463. private void SendSimpleBody (MailMessage message) {
  464. SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
  465. if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
  466. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
  467. SendData (string.Empty);
  468. SendData (EncodeBody (message));
  469. }
  470. private void SendMultipartBody (MailMessage message) {
  471. boundaryIndex = 0;
  472. string boundary = GenerateBoundary ();
  473. // Figure out the message content type
  474. ContentType messageContentType = message.BodyContentType;
  475. messageContentType.Boundary = boundary;
  476. messageContentType.MediaType = "multipart/mixed";
  477. SendHeader (HeaderName.ContentType, messageContentType.ToString ());
  478. if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
  479. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
  480. SendData (string.Empty);
  481. SendData (EncodeBody (message));
  482. SendData (string.Empty);
  483. message.AlternateViews.Add (AlternateView.CreateAlternateViewFromString (message.Body, new ContentType ("text/plain")));
  484. if (message.AlternateViews.Count > 0) {
  485. SendAlternateViews (message, boundary);
  486. }
  487. if (message.Attachments.Count > 0) {
  488. SendAttachments (message, boundary);
  489. }
  490. EndSection (boundary);
  491. }
  492. private void SendAlternateViews (MailMessage message, string boundary) {
  493. AlternateViewCollection alternateViews = message.AlternateViews;
  494. string inner_boundary = GenerateBoundary ();
  495. ContentType messageContentType = message.BodyContentType;
  496. messageContentType.Boundary = inner_boundary;
  497. messageContentType.MediaType = "multipart/alternative";
  498. StartSection (boundary, messageContentType);
  499. for (int i = 0; i < alternateViews.Count; i += 1) {
  500. ContentType contentType = new ContentType (alternateViews [i].ContentType.ToString ());
  501. StartSection (inner_boundary, contentType, alternateViews [i].TransferEncoding);
  502. switch (alternateViews [i].TransferEncoding) {
  503. case TransferEncoding.Base64:
  504. byte [] content = new byte [alternateViews [i].ContentStream.Length];
  505. alternateViews [i].ContentStream.Read (content, 0, content.Length);
  506. #if TARGET_JVM
  507. SendData (Convert.ToBase64String (content));
  508. #else
  509. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  510. #endif
  511. break;
  512. case TransferEncoding.QuotedPrintable:
  513. StreamReader sr = new StreamReader (alternateViews [i].ContentStream);
  514. SendData (ToQuotedPrintable (sr.ReadToEnd (), Encoding.GetEncoding (contentType.CharSet)));
  515. break;
  516. case TransferEncoding.SevenBit:
  517. case TransferEncoding.Unknown:
  518. content = new byte [alternateViews [i].ContentStream.Length];
  519. SendData (Encoding.ASCII.GetString (content));
  520. break;
  521. }
  522. SendData (string.Empty);
  523. }
  524. EndSection (inner_boundary);
  525. }
  526. private void SendAttachments (MailMessage message, string boundary) {
  527. AttachmentCollection attachments = message.Attachments;
  528. for (int i = 0; i < attachments.Count; i += 1) {
  529. ContentType contentType = new ContentType (attachments [i].ContentType.ToString ());
  530. attachments [i].ContentDisposition.FileName = attachments [i].Name;
  531. StartSection (boundary, contentType, attachments [i].TransferEncoding, attachments [i].ContentDisposition);
  532. switch (attachments [i].TransferEncoding) {
  533. case TransferEncoding.Base64:
  534. byte[] content = new byte [attachments [i].ContentStream.Length];
  535. attachments [i].ContentStream.Read (content, 0, content.Length);
  536. #if TARGET_JVM
  537. SendData (Convert.ToBase64String (content));
  538. #else
  539. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  540. #endif
  541. break;
  542. case TransferEncoding.QuotedPrintable:
  543. StreamReader sr = new StreamReader (attachments [i].ContentStream);
  544. SendData (ToQuotedPrintable (sr.ReadToEnd (), Encoding.GetEncoding (contentType.CharSet)));
  545. break;
  546. case TransferEncoding.SevenBit:
  547. case TransferEncoding.Unknown:
  548. content = new byte [attachments [i].ContentStream.Length];
  549. SendData (Encoding.ASCII.GetString (content));
  550. break;
  551. }
  552. SendData (string.Empty);
  553. }
  554. }
  555. private SmtpResponse SendCommand (string command)
  556. {
  557. writer.Write (command);
  558. // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
  559. writer.Write ("\r\n");
  560. writer.Flush ();
  561. return Read ();
  562. }
  563. private void SendHeader (string name, string value)
  564. {
  565. SendData (String.Format ("{0}: {1}", name, value));
  566. }
  567. private void StartSection (string section, ContentType sectionContentType)
  568. {
  569. SendData (string.Empty);
  570. SendData (String.Format ("--{0}", section));
  571. SendHeader ("content-type", sectionContentType.ToString ());
  572. SendData (string.Empty);
  573. }
  574. private void StartSection (string section, ContentType sectionContentType,TransferEncoding transferEncoding)
  575. {
  576. SendData (String.Format ("--{0}", section));
  577. SendHeader ("content-type", sectionContentType.ToString ());
  578. SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
  579. SendData (string.Empty);
  580. }
  581. private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) {
  582. SendData (String.Format ("--{0}", section));
  583. SendHeader ("content-type", sectionContentType.ToString ());
  584. SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding));
  585. SendHeader ("content-disposition", contentDisposition.ToString ());
  586. SendData (string.Empty);
  587. }
  588. // use proper encoding to escape input
  589. private string ToQuotedPrintable (string input, Encoding enc) {
  590. byte [] bytes = enc.GetBytes (input);
  591. StringWriter writer = new StringWriter ();
  592. foreach (byte i in bytes) {
  593. if (i > 127) {
  594. writer.Write ("=");
  595. writer.Write (Convert.ToString (i, 16).ToUpper ());
  596. } else
  597. writer.Write (Convert.ToChar (i));
  598. }
  599. return writer.GetStringBuilder ().ToString ();
  600. }
  601. private static string GetTransferEncodingName (TransferEncoding encoding)
  602. {
  603. switch (encoding) {
  604. case TransferEncoding.QuotedPrintable:
  605. return "quoted-printable";
  606. case TransferEncoding.SevenBit:
  607. return "7bit";
  608. case TransferEncoding.Base64:
  609. return "base64";
  610. }
  611. return "unknown";
  612. }
  613. private void InitiateSecureConnection () {
  614. SmtpResponse response = SendCommand ("STARTTLS");
  615. if (IsError (response)) {
  616. throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
  617. }
  618. ChangeToSSLSocket ();
  619. }
  620. private bool ChangeToSSLSocket () {
  621. #if TARGET_JVM
  622. stream.ChangeToSSLSocket ();
  623. return true;
  624. #else
  625. throw new NotImplementedException ();
  626. #endif
  627. }
  628. void Authenticate ()
  629. {
  630. string user = null, pass = null;
  631. if (UseDefaultCredentials) {
  632. user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
  633. pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
  634. } else if (Credentials != null) {
  635. user = Credentials.GetCredential (host, port, "smtp").UserName;
  636. pass = Credentials.GetCredential (host, port, "smtp").Password;
  637. } else {
  638. return;
  639. }
  640. Authenticate (user, pass);
  641. }
  642. void Authenticate (string Username, string Password)
  643. {
  644. // FIXME: use the proper AuthMech
  645. SmtpResponse status = SendCommand ("AUTH LOGIN");
  646. if (((int) status.StatusCode) != 334) {
  647. throw new SmtpException (status.StatusCode, status.Description);
  648. }
  649. status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Username)));
  650. if (((int) status.StatusCode) != 334) {
  651. throw new SmtpException (status.StatusCode, status.Description);
  652. }
  653. status = SendCommand (Convert.ToBase64String (Encoding.ASCII.GetBytes (Password)));
  654. if (IsError (status)) {
  655. throw new SmtpException (status.StatusCode, status.Description);
  656. }
  657. }
  658. #endregion // Methods
  659. // The HeaderName struct is used to store constant string values representing mail headers.
  660. private struct HeaderName {
  661. public const string ContentTransferEncoding = "Content-Transfer-Encoding";
  662. public const string ContentType = "Content-Type";
  663. public const string Bcc = "Bcc";
  664. public const string Cc = "Cc";
  665. public const string From = "From";
  666. public const string Subject = "Subject";
  667. public const string To = "To";
  668. public const string MimeVersion = "MIME-Version";
  669. public const string MessageId = "Message-ID";
  670. public const string Priority = "Priority";
  671. public const string Importance = "Importance";
  672. public const string XPriority = "X-Priority";
  673. public const string Date = "Date";
  674. }
  675. // This object encapsulates the status code and description of an SMTP response.
  676. private struct SmtpResponse {
  677. public SmtpStatusCode StatusCode;
  678. public string Description;
  679. public static SmtpResponse Parse (string line) {
  680. SmtpResponse response = new SmtpResponse ();
  681. if (line.Length < 4)
  682. throw new SmtpException ("Response is to short " +
  683. line.Length + ".");
  684. if ((line [3] != ' ') && (line [3] != '-'))
  685. throw new SmtpException ("Response format is wrong.(" +
  686. line + ")");
  687. // parse the response code
  688. response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
  689. // set the raw response
  690. response.Description = line;
  691. return response;
  692. }
  693. }
  694. }
  695. class CCredentialsByHost : ICredentialsByHost
  696. {
  697. public CCredentialsByHost (string userName, string password) {
  698. this.userName = userName;
  699. this.password = password;
  700. }
  701. public NetworkCredential GetCredential (string host, int port, string authenticationType) {
  702. return new NetworkCredential (userName, password);
  703. }
  704. private string userName;
  705. private string password;
  706. }
  707. }
  708. #endif // NET_2_0