SmtpClient.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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 SECURITY_DEP
  30. extern alias PrebuiltSystem;
  31. #endif
  32. using System;
  33. using System.Collections.Generic;
  34. using System.ComponentModel;
  35. using System.Globalization;
  36. using System.IO;
  37. using System.Net;
  38. using System.Net.Mime;
  39. using System.Net.Sockets;
  40. using System.Security.Cryptography.X509Certificates;
  41. using System.Text;
  42. using System.Threading;
  43. using System.Reflection;
  44. using System.Net.Configuration;
  45. using System.Configuration;
  46. using System.Net.Security;
  47. using System.Security.Authentication;
  48. #if SECURITY_DEP
  49. using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
  50. #endif
  51. namespace System.Net.Mail {
  52. public class SmtpClient
  53. #if NET_4_0
  54. : IDisposable
  55. #endif
  56. {
  57. #region Fields
  58. string host;
  59. int port;
  60. int timeout = 100000;
  61. ICredentialsByHost credentials;
  62. string pickupDirectoryLocation;
  63. SmtpDeliveryMethod deliveryMethod;
  64. bool enableSsl;
  65. #if SECURITY_DEP
  66. X509CertificateCollection clientCertificates;
  67. #endif
  68. TcpClient client;
  69. Stream stream;
  70. StreamWriter writer;
  71. StreamReader reader;
  72. int boundaryIndex;
  73. MailAddress defaultFrom;
  74. MailMessage messageInProcess;
  75. BackgroundWorker worker;
  76. object user_async_state;
  77. [Flags]
  78. enum AuthMechs {
  79. None = 0,
  80. Login = 0x01,
  81. Plain = 0x02,
  82. }
  83. class CancellationException : Exception
  84. {
  85. }
  86. AuthMechs authMechs;
  87. Mutex mutex = new Mutex ();
  88. #endregion // Fields
  89. #region Constructors
  90. public SmtpClient ()
  91. : this (null, 0)
  92. {
  93. }
  94. public SmtpClient (string host)
  95. : this (host, 0)
  96. {
  97. }
  98. public SmtpClient (string host, int port) {
  99. #if CONFIGURATION_DEP
  100. SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
  101. if (cfg != null) {
  102. this.host = cfg.Network.Host;
  103. this.port = cfg.Network.Port;
  104. #if NET_4_0
  105. this.enableSsl = cfg.Network.EnableSsl;
  106. #endif
  107. TargetName = cfg.Network.TargetName;
  108. if (this.TargetName == null)
  109. TargetName = "SMTPSVC/" + (host != null ? host : "");
  110. if (cfg.Network.UserName != null) {
  111. string password = String.Empty;
  112. if (cfg.Network.Password != null)
  113. password = cfg.Network.Password;
  114. Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
  115. }
  116. if (!String.IsNullOrEmpty (cfg.From))
  117. defaultFrom = new MailAddress (cfg.From);
  118. }
  119. #else
  120. // Just to eliminate the warning, this codepath does not end up in production.
  121. defaultFrom = null;
  122. #endif
  123. if (!String.IsNullOrEmpty (host))
  124. this.host = host;
  125. if (port != 0)
  126. this.port = port;
  127. }
  128. #endregion // Constructors
  129. #region Properties
  130. #if SECURITY_DEP
  131. [MonoTODO("Client certificates not used")]
  132. public X509CertificateCollection ClientCertificates {
  133. get {
  134. if (clientCertificates == null)
  135. clientCertificates = new X509CertificateCollection ();
  136. return clientCertificates;
  137. }
  138. }
  139. #endif
  140. #if NET_4_0
  141. public
  142. #endif
  143. string TargetName { get; set; }
  144. public ICredentialsByHost Credentials {
  145. get { return credentials; }
  146. set {
  147. CheckState ();
  148. credentials = value;
  149. }
  150. }
  151. public SmtpDeliveryMethod DeliveryMethod {
  152. get { return deliveryMethod; }
  153. set {
  154. CheckState ();
  155. deliveryMethod = value;
  156. }
  157. }
  158. public bool EnableSsl {
  159. get { return enableSsl; }
  160. set {
  161. CheckState ();
  162. enableSsl = value;
  163. }
  164. }
  165. public string Host {
  166. get { return host; }
  167. set {
  168. if (value == null)
  169. throw new ArgumentNullException ("value");
  170. if (value.Length == 0)
  171. throw new ArgumentException ("An empty string is not allowed.", "value");
  172. CheckState ();
  173. host = value;
  174. }
  175. }
  176. public string PickupDirectoryLocation {
  177. get { return pickupDirectoryLocation; }
  178. set { pickupDirectoryLocation = value; }
  179. }
  180. public int Port {
  181. get { return port; }
  182. set {
  183. if (value <= 0)
  184. throw new ArgumentOutOfRangeException ("value");
  185. CheckState ();
  186. port = value;
  187. }
  188. }
  189. [MonoTODO]
  190. public ServicePoint ServicePoint {
  191. get { throw new NotImplementedException (); }
  192. }
  193. public int Timeout {
  194. get { return timeout; }
  195. set {
  196. if (value < 0)
  197. throw new ArgumentOutOfRangeException ("value");
  198. CheckState ();
  199. timeout = value;
  200. }
  201. }
  202. public bool UseDefaultCredentials {
  203. get { return false; }
  204. [MonoNotSupported ("no DefaultCredential support in Mono")]
  205. set {
  206. if (value)
  207. throw new NotImplementedException ("Default credentials are not supported");
  208. CheckState ();
  209. }
  210. }
  211. #endregion // Properties
  212. #region Events
  213. public event SendCompletedEventHandler SendCompleted;
  214. #endregion // Events
  215. #region Methods
  216. #if NET_4_0
  217. public void Dispose ()
  218. {
  219. Dispose (true);
  220. }
  221. [MonoTODO ("Does nothing at the moment.")]
  222. protected virtual void Dispose (bool disposing)
  223. {
  224. // TODO: We should close all the connections and abort any async operations here
  225. }
  226. #endif
  227. private void CheckState ()
  228. {
  229. if (messageInProcess != null)
  230. throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
  231. }
  232. private static string EncodeAddress(MailAddress address)
  233. {
  234. if (!String.IsNullOrEmpty (address.DisplayName)) {
  235. string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
  236. return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
  237. }
  238. return address.ToString ();
  239. }
  240. private static string EncodeAddresses(MailAddressCollection addresses)
  241. {
  242. StringBuilder sb = new StringBuilder();
  243. bool first = true;
  244. foreach (MailAddress address in addresses) {
  245. if (!first) {
  246. sb.Append(", ");
  247. }
  248. sb.Append(EncodeAddress(address));
  249. first = false;
  250. }
  251. return sb.ToString();
  252. }
  253. private string EncodeSubjectRFC2047 (MailMessage message)
  254. {
  255. return ContentType.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
  256. }
  257. private string EncodeBody (MailMessage message)
  258. {
  259. string body = message.Body;
  260. Encoding encoding = message.BodyEncoding;
  261. // RFC 2045 encoding
  262. switch (message.ContentTransferEncoding) {
  263. case TransferEncoding.SevenBit:
  264. return body;
  265. case TransferEncoding.Base64:
  266. return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
  267. default:
  268. return ToQuotedPrintable (body, encoding);
  269. }
  270. }
  271. private string EncodeBody (AlternateView av)
  272. {
  273. //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
  274. byte [] bytes = new byte [av.ContentStream.Length];
  275. av.ContentStream.Read (bytes, 0, bytes.Length);
  276. // RFC 2045 encoding
  277. switch (av.TransferEncoding) {
  278. case TransferEncoding.SevenBit:
  279. return Encoding.ASCII.GetString (bytes);
  280. case TransferEncoding.Base64:
  281. return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
  282. default:
  283. return ToQuotedPrintable (bytes);
  284. }
  285. }
  286. private void EndSection (string section)
  287. {
  288. SendData (String.Format ("--{0}--", section));
  289. SendData (string.Empty);
  290. }
  291. private string GenerateBoundary ()
  292. {
  293. string output = GenerateBoundary (boundaryIndex);
  294. boundaryIndex += 1;
  295. return output;
  296. }
  297. private static string GenerateBoundary (int index)
  298. {
  299. return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
  300. }
  301. private bool IsError (SmtpResponse status)
  302. {
  303. return ((int) status.StatusCode) >= 400;
  304. }
  305. protected void OnSendCompleted (AsyncCompletedEventArgs e)
  306. {
  307. try {
  308. if (SendCompleted != null)
  309. SendCompleted (this, e);
  310. } finally {
  311. worker = null;
  312. user_async_state = null;
  313. }
  314. }
  315. private void CheckCancellation ()
  316. {
  317. if (worker != null && worker.CancellationPending)
  318. throw new CancellationException ();
  319. }
  320. private SmtpResponse Read () {
  321. byte [] buffer = new byte [512];
  322. int position = 0;
  323. bool lastLine = false;
  324. do {
  325. CheckCancellation ();
  326. int readLength = stream.Read (buffer, position, buffer.Length - position);
  327. if (readLength > 0) {
  328. int available = position + readLength - 1;
  329. if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
  330. for (int index = available - 3; ; index--) {
  331. if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
  332. lastLine = buffer [index + 4] == ' ';
  333. break;
  334. }
  335. }
  336. // move position
  337. position += readLength;
  338. // check if buffer is full
  339. if (position == buffer.Length) {
  340. byte [] newBuffer = new byte [buffer.Length * 2];
  341. Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
  342. buffer = newBuffer;
  343. }
  344. }
  345. else {
  346. break;
  347. }
  348. } while (!lastLine);
  349. if (position > 0) {
  350. Encoding encoding = new ASCIIEncoding ();
  351. string line = encoding.GetString (buffer, 0, position - 1);
  352. // parse the line to the lastResponse object
  353. SmtpResponse response = SmtpResponse.Parse (line);
  354. return response;
  355. } else {
  356. throw new System.IO.IOException ("Connection closed");
  357. }
  358. }
  359. void ResetExtensions()
  360. {
  361. authMechs = AuthMechs.None;
  362. }
  363. void ParseExtensions (string extens)
  364. {
  365. string[] parts = extens.Split ('\n');
  366. foreach (string part in parts) {
  367. if (part.Length < 4)
  368. continue;
  369. string start = part.Substring (4);
  370. if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
  371. string[] options = start.Split (' ');
  372. for (int k = 1; k < options.Length; k++) {
  373. string option = options[k].Trim();
  374. // GSSAPI, KERBEROS_V4, NTLM not supported
  375. switch (option) {
  376. /*
  377. case "CRAM-MD5":
  378. authMechs |= AuthMechs.CramMD5;
  379. break;
  380. case "DIGEST-MD5":
  381. authMechs |= AuthMechs.DigestMD5;
  382. break;
  383. */
  384. case "LOGIN":
  385. authMechs |= AuthMechs.Login;
  386. break;
  387. case "PLAIN":
  388. authMechs |= AuthMechs.Plain;
  389. break;
  390. }
  391. }
  392. }
  393. }
  394. }
  395. public void Send (MailMessage message)
  396. {
  397. if (message == null)
  398. throw new ArgumentNullException ("message");
  399. if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
  400. throw new InvalidOperationException ("The SMTP host was not specified");
  401. else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
  402. throw new NotSupportedException("IIS delivery is not supported");
  403. if (port == 0)
  404. port = 25;
  405. // Block while sending
  406. mutex.WaitOne ();
  407. try {
  408. messageInProcess = message;
  409. if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
  410. SendToFile (message);
  411. else
  412. SendInternal (message);
  413. } catch (CancellationException) {
  414. // This exception is introduced for convenient cancellation process.
  415. } catch (SmtpException) {
  416. throw;
  417. } catch (Exception ex) {
  418. throw new SmtpException ("Message could not be sent.", ex);
  419. } finally {
  420. // Release the mutex to allow other threads access
  421. mutex.ReleaseMutex ();
  422. messageInProcess = null;
  423. }
  424. }
  425. private void SendInternal (MailMessage message)
  426. {
  427. CheckCancellation ();
  428. try {
  429. client = new TcpClient (host, port);
  430. stream = client.GetStream ();
  431. // FIXME: this StreamWriter creation is bogus.
  432. // It expects as if a Stream were able to switch to SSL
  433. // mode (such behavior is only in Mainsoft Socket API).
  434. writer = new StreamWriter (stream);
  435. reader = new StreamReader (stream);
  436. SendCore (message);
  437. } finally {
  438. if (writer != null)
  439. writer.Close ();
  440. if (reader != null)
  441. reader.Close ();
  442. if (stream != null)
  443. stream.Close ();
  444. if (client != null)
  445. client.Close ();
  446. }
  447. }
  448. // FIXME: simple implementation, could be brushed up.
  449. private void SendToFile (MailMessage message)
  450. {
  451. if (!Path.IsPathRooted (pickupDirectoryLocation))
  452. throw new SmtpException("Only absolute directories are allowed for pickup directory.");
  453. string filename = Path.Combine (pickupDirectoryLocation,
  454. Guid.NewGuid() + ".eml");
  455. try {
  456. writer = new StreamWriter(filename);
  457. // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
  458. // For all we know, defaultFrom may be the envelope sender
  459. // For now, we are no worse than some versions of .NET
  460. MailAddress from = message.From;
  461. if (from == null)
  462. from = defaultFrom;
  463. SendHeader (HeaderName.Date, DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
  464. SendHeader (HeaderName.From, EncodeAddress(from));
  465. SendHeader (HeaderName.To, EncodeAddresses(message.To));
  466. if (message.CC.Count > 0)
  467. SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
  468. SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
  469. foreach (string s in message.Headers.AllKeys)
  470. SendHeader (s, message.Headers [s]);
  471. AddPriorityHeader (message);
  472. boundaryIndex = 0;
  473. if (message.Attachments.Count > 0)
  474. SendWithAttachments (message);
  475. else
  476. SendWithoutAttachments (message, null, false);
  477. } finally {
  478. if (writer != null) writer.Close(); writer = null;
  479. }
  480. }
  481. private void SendCore (MailMessage message)
  482. {
  483. SmtpResponse status;
  484. status = Read ();
  485. if (IsError (status))
  486. throw new SmtpException (status.StatusCode, status.Description);
  487. // EHLO
  488. // FIXME: parse the list of extensions so we don't bother wasting
  489. // our time trying commands if they aren't supported.
  490. status = SendCommand ("EHLO " + Dns.GetHostName ());
  491. if (IsError (status)) {
  492. status = SendCommand ("HELO " + Dns.GetHostName ());
  493. if (IsError (status))
  494. throw new SmtpException (status.StatusCode, status.Description);
  495. } else {
  496. // Parse ESMTP extensions
  497. string extens = status.Description;
  498. if (extens != null)
  499. ParseExtensions (extens);
  500. }
  501. if (enableSsl) {
  502. InitiateSecureConnection ();
  503. ResetExtensions();
  504. writer = new StreamWriter (stream);
  505. reader = new StreamReader (stream);
  506. status = SendCommand ("EHLO " + Dns.GetHostName ());
  507. if (IsError (status)) {
  508. status = SendCommand ("HELO " + Dns.GetHostName ());
  509. if (IsError (status))
  510. throw new SmtpException (status.StatusCode, status.Description);
  511. } else {
  512. // Parse ESMTP extensions
  513. string extens = status.Description;
  514. if (extens != null)
  515. ParseExtensions (extens);
  516. }
  517. }
  518. if (authMechs != AuthMechs.None)
  519. Authenticate ();
  520. // The envelope sender: use 'Sender:' in preference of 'From:'
  521. MailAddress sender = message.Sender;
  522. if (sender == null)
  523. sender = message.From;
  524. if (sender == null)
  525. sender = defaultFrom;
  526. // MAIL FROM:
  527. status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
  528. if (IsError (status)) {
  529. throw new SmtpException (status.StatusCode, status.Description);
  530. }
  531. // Send RCPT TO: for all recipients
  532. List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
  533. for (int i = 0; i < message.To.Count; i ++) {
  534. status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
  535. if (IsError (status))
  536. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
  537. }
  538. for (int i = 0; i < message.CC.Count; i ++) {
  539. status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
  540. if (IsError (status))
  541. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
  542. }
  543. for (int i = 0; i < message.Bcc.Count; i ++) {
  544. status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
  545. if (IsError (status))
  546. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
  547. }
  548. #if TARGET_JVM // List<T>.ToArray () is not supported
  549. if (sfre.Count > 0) {
  550. SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
  551. sfre.CopyTo (xs);
  552. throw new SmtpFailedRecipientsException ("failed recipients", xs);
  553. }
  554. #else
  555. if (sfre.Count >0)
  556. throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
  557. #endif
  558. // DATA
  559. status = SendCommand ("DATA");
  560. if (IsError (status))
  561. throw new SmtpException (status.StatusCode, status.Description);
  562. // Send message headers
  563. string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
  564. // remove ':' from time zone offset (e.g. from "+01:00")
  565. dt = dt.Remove (dt.Length - 3, 1);
  566. SendHeader (HeaderName.Date, dt);
  567. MailAddress from = message.From;
  568. if (from == null)
  569. from = defaultFrom;
  570. SendHeader (HeaderName.From, EncodeAddress (from));
  571. SendHeader (HeaderName.To, EncodeAddresses (message.To));
  572. if (message.CC.Count > 0)
  573. SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
  574. SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
  575. string v = "normal";
  576. switch (message.Priority){
  577. case MailPriority.Normal:
  578. v = "normal";
  579. break;
  580. case MailPriority.Low:
  581. v = "non-urgent";
  582. break;
  583. case MailPriority.High:
  584. v = "urgent";
  585. break;
  586. }
  587. SendHeader ("Priority", v);
  588. if (message.Sender != null)
  589. SendHeader ("Sender", EncodeAddress (message.Sender));
  590. if (message.ReplyToList.Count > 0)
  591. SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
  592. #if NET_4_0
  593. foreach (string s in message.Headers.AllKeys)
  594. SendHeader (s, ContentType.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
  595. #else
  596. foreach (string s in message.Headers.AllKeys)
  597. SendHeader (s, message.Headers [s]);
  598. #endif
  599. AddPriorityHeader (message);
  600. boundaryIndex = 0;
  601. if (message.Attachments.Count > 0)
  602. SendWithAttachments (message);
  603. else
  604. SendWithoutAttachments (message, null, false);
  605. SendDot ();
  606. status = Read ();
  607. if (IsError (status))
  608. throw new SmtpException (status.StatusCode, status.Description);
  609. try {
  610. status = SendCommand ("QUIT");
  611. } catch (System.IO.IOException) {
  612. // We excuse server for the rude connection closing as a response to QUIT
  613. }
  614. }
  615. public void Send (string from, string to, string subject, string body)
  616. {
  617. Send (new MailMessage (from, to, subject, body));
  618. }
  619. private void SendDot()
  620. {
  621. writer.Write(".\r\n");
  622. writer.Flush();
  623. }
  624. private void SendData (string data)
  625. {
  626. if (String.IsNullOrEmpty (data)) {
  627. writer.Write("\r\n");
  628. writer.Flush();
  629. return;
  630. }
  631. StringReader sr = new StringReader (data);
  632. string line;
  633. bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
  634. while ((line = sr.ReadLine ()) != null) {
  635. CheckCancellation ();
  636. if (escapeDots) {
  637. int i;
  638. for (i = 0; i < line.Length; i++) {
  639. if (line[i] != '.')
  640. break;
  641. }
  642. if (i > 0 && i == line.Length) {
  643. line += ".";
  644. }
  645. }
  646. writer.Write (line);
  647. writer.Write ("\r\n");
  648. }
  649. writer.Flush ();
  650. }
  651. public void SendAsync (MailMessage message, object userToken)
  652. {
  653. if (worker != null)
  654. throw new InvalidOperationException ("Another SendAsync operation is in progress");
  655. worker = new BackgroundWorker ();
  656. worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
  657. try {
  658. user_async_state = ea.Argument;
  659. Send (message);
  660. } catch (Exception ex) {
  661. ea.Result = ex;
  662. throw ex;
  663. }
  664. };
  665. worker.WorkerSupportsCancellation = true;
  666. worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
  667. // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
  668. OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
  669. };
  670. worker.RunWorkerAsync (userToken);
  671. }
  672. public void SendAsync (string from, string to, string subject, string body, object userToken)
  673. {
  674. SendAsync (new MailMessage (from, to, subject, body), userToken);
  675. }
  676. public void SendAsyncCancel ()
  677. {
  678. if (worker == null)
  679. throw new InvalidOperationException ("SendAsync operation is not in progress");
  680. worker.CancelAsync ();
  681. }
  682. private void AddPriorityHeader (MailMessage message) {
  683. switch (message.Priority) {
  684. case MailPriority.High:
  685. SendHeader (HeaderName.Priority, "Urgent");
  686. SendHeader (HeaderName.Importance, "high");
  687. SendHeader (HeaderName.XPriority, "1");
  688. break;
  689. case MailPriority.Low:
  690. SendHeader (HeaderName.Priority, "Non-Urgent");
  691. SendHeader (HeaderName.Importance, "low");
  692. SendHeader (HeaderName.XPriority, "5");
  693. break;
  694. }
  695. }
  696. private void SendSimpleBody (MailMessage message) {
  697. SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
  698. if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
  699. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
  700. SendData (string.Empty);
  701. SendData (EncodeBody (message));
  702. }
  703. private void SendBodylessSingleAlternate (AlternateView av) {
  704. SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
  705. if (av.TransferEncoding != TransferEncoding.SevenBit)
  706. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
  707. SendData (string.Empty);
  708. SendData (EncodeBody (av));
  709. }
  710. private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
  711. {
  712. if (message.Body == null && message.AlternateViews.Count == 1)
  713. SendBodylessSingleAlternate (message.AlternateViews [0]);
  714. else if (message.AlternateViews.Count > 0)
  715. SendBodyWithAlternateViews (message, boundary, attachmentExists);
  716. else
  717. SendSimpleBody (message);
  718. }
  719. private void SendWithAttachments (MailMessage message) {
  720. string boundary = GenerateBoundary ();
  721. // first "multipart/mixed"
  722. ContentType messageContentType = new ContentType ();
  723. messageContentType.Boundary = boundary;
  724. messageContentType.MediaType = "multipart/mixed";
  725. messageContentType.CharSet = null;
  726. SendHeader (HeaderName.ContentType, messageContentType.ToString ());
  727. SendData (String.Empty);
  728. // body section
  729. Attachment body = null;
  730. if (message.AlternateViews.Count > 0)
  731. SendWithoutAttachments (message, boundary, true);
  732. else {
  733. body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
  734. message.Attachments.Insert (0, body);
  735. }
  736. try {
  737. SendAttachments (message, body, boundary);
  738. } finally {
  739. if (body != null)
  740. message.Attachments.Remove (body);
  741. }
  742. EndSection (boundary);
  743. }
  744. private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
  745. {
  746. AlternateViewCollection alternateViews = message.AlternateViews;
  747. string inner_boundary = GenerateBoundary ();
  748. ContentType messageContentType = new ContentType ();
  749. messageContentType.Boundary = inner_boundary;
  750. messageContentType.MediaType = "multipart/alternative";
  751. if (!attachmentExists) {
  752. SendHeader (HeaderName.ContentType, messageContentType.ToString ());
  753. SendData (String.Empty);
  754. }
  755. // body section
  756. AlternateView body = null;
  757. if (message.Body != null) {
  758. body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
  759. alternateViews.Insert (0, body);
  760. StartSection (boundary, messageContentType);
  761. }
  762. try {
  763. // alternate view sections
  764. foreach (AlternateView av in alternateViews) {
  765. string alt_boundary = null;
  766. ContentType contentType;
  767. if (av.LinkedResources.Count > 0) {
  768. alt_boundary = GenerateBoundary ();
  769. contentType = new ContentType ("multipart/related");
  770. contentType.Boundary = alt_boundary;
  771. contentType.Parameters ["type"] = av.ContentType.ToString ();
  772. StartSection (inner_boundary, contentType);
  773. StartSection (alt_boundary, av.ContentType, av);
  774. } else {
  775. contentType = new ContentType (av.ContentType.ToString ());
  776. StartSection (inner_boundary, contentType, av);
  777. }
  778. switch (av.TransferEncoding) {
  779. case TransferEncoding.Base64:
  780. byte [] content = new byte [av.ContentStream.Length];
  781. av.ContentStream.Read (content, 0, content.Length);
  782. #if TARGET_JVM
  783. SendData (Convert.ToBase64String (content));
  784. #else
  785. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  786. #endif
  787. break;
  788. case TransferEncoding.QuotedPrintable:
  789. byte [] bytes = new byte [av.ContentStream.Length];
  790. av.ContentStream.Read (bytes, 0, bytes.Length);
  791. SendData (ToQuotedPrintable (bytes));
  792. break;
  793. case TransferEncoding.SevenBit:
  794. case TransferEncoding.Unknown:
  795. content = new byte [av.ContentStream.Length];
  796. av.ContentStream.Read (content, 0, content.Length);
  797. SendData (Encoding.ASCII.GetString (content));
  798. break;
  799. }
  800. if (av.LinkedResources.Count > 0) {
  801. SendLinkedResources (message, av.LinkedResources, alt_boundary);
  802. EndSection (alt_boundary);
  803. }
  804. if (!attachmentExists)
  805. SendData (string.Empty);
  806. }
  807. } finally {
  808. if (body != null)
  809. alternateViews.Remove (body);
  810. }
  811. EndSection (inner_boundary);
  812. }
  813. private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
  814. {
  815. foreach (LinkedResource lr in resources) {
  816. StartSection (boundary, lr.ContentType, lr);
  817. switch (lr.TransferEncoding) {
  818. case TransferEncoding.Base64:
  819. byte [] content = new byte [lr.ContentStream.Length];
  820. lr.ContentStream.Read (content, 0, content.Length);
  821. #if TARGET_JVM
  822. SendData (Convert.ToBase64String (content));
  823. #else
  824. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  825. #endif
  826. break;
  827. case TransferEncoding.QuotedPrintable:
  828. byte [] bytes = new byte [lr.ContentStream.Length];
  829. lr.ContentStream.Read (bytes, 0, bytes.Length);
  830. SendData (ToQuotedPrintable (bytes));
  831. break;
  832. case TransferEncoding.SevenBit:
  833. case TransferEncoding.Unknown:
  834. content = new byte [lr.ContentStream.Length];
  835. lr.ContentStream.Read (content, 0, content.Length);
  836. SendData (Encoding.ASCII.GetString (content));
  837. break;
  838. }
  839. }
  840. }
  841. private void SendAttachments (MailMessage message, Attachment body, string boundary) {
  842. foreach (Attachment att in message.Attachments) {
  843. ContentType contentType = new ContentType (att.ContentType.ToString ());
  844. if (att.Name != null) {
  845. contentType.Name = att.Name;
  846. if (att.NameEncoding != null)
  847. contentType.CharSet = att.NameEncoding.HeaderName;
  848. att.ContentDisposition.FileName = att.Name;
  849. }
  850. StartSection (boundary, contentType, att, att != body);
  851. byte [] content = new byte [att.ContentStream.Length];
  852. att.ContentStream.Read (content, 0, content.Length);
  853. switch (att.TransferEncoding) {
  854. case TransferEncoding.Base64:
  855. #if TARGET_JVM
  856. SendData (Convert.ToBase64String (content));
  857. #else
  858. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  859. #endif
  860. break;
  861. case TransferEncoding.QuotedPrintable:
  862. SendData (ToQuotedPrintable (content));
  863. break;
  864. case TransferEncoding.SevenBit:
  865. case TransferEncoding.Unknown:
  866. SendData (Encoding.ASCII.GetString (content));
  867. break;
  868. }
  869. SendData (string.Empty);
  870. }
  871. }
  872. private SmtpResponse SendCommand (string command)
  873. {
  874. writer.Write (command);
  875. // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
  876. writer.Write ("\r\n");
  877. writer.Flush ();
  878. return Read ();
  879. }
  880. private void SendHeader (string name, string value)
  881. {
  882. SendData (String.Format ("{0}: {1}", name, value));
  883. }
  884. private void StartSection (string section, ContentType sectionContentType)
  885. {
  886. SendData (String.Format ("--{0}", section));
  887. SendHeader ("content-type", sectionContentType.ToString ());
  888. SendData (string.Empty);
  889. }
  890. private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
  891. {
  892. SendData (String.Format ("--{0}", section));
  893. SendHeader ("content-type", sectionContentType.ToString ());
  894. SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
  895. if (!string.IsNullOrEmpty (att.ContentId))
  896. SendHeader("content-ID", "<" + att.ContentId + ">");
  897. SendData (string.Empty);
  898. }
  899. private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
  900. SendData (String.Format ("--{0}", section));
  901. if (!string.IsNullOrEmpty (att.ContentId))
  902. SendHeader("content-ID", "<" + att.ContentId + ">");
  903. SendHeader ("content-type", sectionContentType.ToString ());
  904. SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
  905. if (sendDisposition)
  906. SendHeader ("content-disposition", att.ContentDisposition.ToString ());
  907. SendData (string.Empty);
  908. }
  909. // use proper encoding to escape input
  910. private string ToQuotedPrintable (string input, Encoding enc)
  911. {
  912. byte [] bytes = enc.GetBytes (input);
  913. return ToQuotedPrintable (bytes);
  914. }
  915. private string ToQuotedPrintable (byte [] bytes)
  916. {
  917. StringWriter writer = new StringWriter ();
  918. int charsInLine = 0;
  919. int curLen;
  920. StringBuilder sb = new StringBuilder("=", 3);
  921. byte equalSign = (byte)'=';
  922. char c = (char)0;
  923. foreach (byte i in bytes) {
  924. if (i > 127 || i == equalSign) {
  925. sb.Length = 1;
  926. sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
  927. curLen = 3;
  928. } else {
  929. c = Convert.ToChar (i);
  930. if (c == '\r' || c == '\n') {
  931. writer.Write (c);
  932. charsInLine = 0;
  933. continue;
  934. }
  935. curLen = 1;
  936. }
  937. charsInLine += curLen;
  938. if (charsInLine > 75) {
  939. writer.Write ("=\r\n");
  940. charsInLine = curLen;
  941. }
  942. if (curLen == 1)
  943. writer.Write (c);
  944. else
  945. writer.Write (sb.ToString ());
  946. }
  947. return writer.ToString ();
  948. }
  949. private static string GetTransferEncodingName (TransferEncoding encoding)
  950. {
  951. switch (encoding) {
  952. case TransferEncoding.QuotedPrintable:
  953. return "quoted-printable";
  954. case TransferEncoding.SevenBit:
  955. return "7bit";
  956. case TransferEncoding.Base64:
  957. return "base64";
  958. }
  959. return "unknown";
  960. }
  961. #if SECURITY_DEP
  962. RemoteCertificateValidationCallback callback = delegate (object sender,
  963. X509Certificate certificate,
  964. X509Chain chain,
  965. SslPolicyErrors sslPolicyErrors) {
  966. // honor any exciting callback defined on ServicePointManager
  967. if (ServicePointManager.ServerCertificateValidationCallback != null)
  968. return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
  969. // otherwise provide our own
  970. if (sslPolicyErrors != SslPolicyErrors.None)
  971. throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
  972. return true;
  973. };
  974. #endif
  975. private void InitiateSecureConnection () {
  976. SmtpResponse response = SendCommand ("STARTTLS");
  977. if (IsError (response)) {
  978. throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
  979. }
  980. #if TARGET_JVM
  981. ((NetworkStream) stream).ChangeToSSLSocket ();
  982. #elif SECURITY_DEP
  983. SslStream sslStream = new SslStream (stream, false, callback, null);
  984. CheckCancellation ();
  985. sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
  986. stream = sslStream;
  987. #else
  988. throw new SystemException ("You are using an incomplete System.dll build");
  989. #endif
  990. }
  991. void Authenticate ()
  992. {
  993. string user = null, pass = null;
  994. if (UseDefaultCredentials) {
  995. user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
  996. pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
  997. } else if (Credentials != null) {
  998. user = Credentials.GetCredential (host, port, "smtp").UserName;
  999. pass = Credentials.GetCredential (host, port, "smtp").Password;
  1000. } else {
  1001. return;
  1002. }
  1003. Authenticate (user, pass);
  1004. }
  1005. void CheckStatus (SmtpResponse status, int i)
  1006. {
  1007. if (((int) status.StatusCode) != i)
  1008. throw new SmtpException (status.StatusCode, status.Description);
  1009. }
  1010. void ThrowIfError (SmtpResponse status)
  1011. {
  1012. if (IsError (status))
  1013. throw new SmtpException (status.StatusCode, status.Description);
  1014. }
  1015. void Authenticate (string user, string password)
  1016. {
  1017. if (authMechs == AuthMechs.None)
  1018. return;
  1019. SmtpResponse status;
  1020. /*
  1021. if ((authMechs & AuthMechs.DigestMD5) != 0) {
  1022. status = SendCommand ("AUTH DIGEST-MD5");
  1023. CheckStatus (status, 334);
  1024. string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
  1025. Console.WriteLine ("CHALLENGE: {0}", challenge);
  1026. DigestSession session = new DigestSession ();
  1027. session.Parse (false, challenge);
  1028. string response = session.Authenticate (this, user, password);
  1029. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
  1030. CheckStatus (status, 235);
  1031. } else */
  1032. if ((authMechs & AuthMechs.Login) != 0) {
  1033. status = SendCommand ("AUTH LOGIN");
  1034. CheckStatus (status, 334);
  1035. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
  1036. CheckStatus (status, 334);
  1037. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
  1038. CheckStatus (status, 235);
  1039. } else if ((authMechs & AuthMechs.Plain) != 0) {
  1040. string s = String.Format ("\0{0}\0{1}", user, password);
  1041. s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
  1042. status = SendCommand ("AUTH PLAIN " + s);
  1043. CheckStatus (status, 235);
  1044. } else {
  1045. throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
  1046. }
  1047. }
  1048. #endregion // Methods
  1049. // The HeaderName struct is used to store constant string values representing mail headers.
  1050. private struct HeaderName {
  1051. public const string ContentTransferEncoding = "Content-Transfer-Encoding";
  1052. public const string ContentType = "Content-Type";
  1053. public const string Bcc = "Bcc";
  1054. public const string Cc = "Cc";
  1055. public const string From = "From";
  1056. public const string Subject = "Subject";
  1057. public const string To = "To";
  1058. public const string MimeVersion = "MIME-Version";
  1059. public const string MessageId = "Message-ID";
  1060. public const string Priority = "Priority";
  1061. public const string Importance = "Importance";
  1062. public const string XPriority = "X-Priority";
  1063. public const string Date = "Date";
  1064. }
  1065. // This object encapsulates the status code and description of an SMTP response.
  1066. private struct SmtpResponse {
  1067. public SmtpStatusCode StatusCode;
  1068. public string Description;
  1069. public static SmtpResponse Parse (string line) {
  1070. SmtpResponse response = new SmtpResponse ();
  1071. if (line.Length < 4)
  1072. throw new SmtpException ("Response is to short " +
  1073. line.Length + ".");
  1074. if ((line [3] != ' ') && (line [3] != '-'))
  1075. throw new SmtpException ("Response format is wrong.(" +
  1076. line + ")");
  1077. // parse the response code
  1078. response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
  1079. // set the raw response
  1080. response.Description = line;
  1081. return response;
  1082. }
  1083. }
  1084. }
  1085. class CCredentialsByHost : ICredentialsByHost
  1086. {
  1087. public CCredentialsByHost (string userName, string password) {
  1088. this.userName = userName;
  1089. this.password = password;
  1090. }
  1091. public NetworkCredential GetCredential (string host, int port, string authenticationType) {
  1092. return new NetworkCredential (userName, password);
  1093. }
  1094. private string userName;
  1095. private string password;
  1096. }
  1097. }