SmtpClient.cs 37 KB

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