SmtpClient.cs 36 KB

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