SmtpClient.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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_SECURITY_ALIAS
  34. using MSI = MonoSecurity::Mono.Security.Interface;
  35. #else
  36. using MSI = Mono.Security.Interface;
  37. #endif
  38. using System.Security.Cryptography.X509Certificates;
  39. #endif
  40. using System;
  41. using System.Collections.Generic;
  42. using System.ComponentModel;
  43. using System.Globalization;
  44. using System.IO;
  45. using System.Net;
  46. using System.Net.Mime;
  47. using System.Net.Sockets;
  48. using System.Text;
  49. using System.Threading;
  50. using System.Net.Configuration;
  51. using System.Configuration;
  52. using System.Net.Security;
  53. using System.Security.Authentication;
  54. using System.Threading.Tasks;
  55. using Mono.Net.Security;
  56. namespace System.Net.Mail {
  57. [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")]
  58. public class SmtpClient
  59. : IDisposable
  60. {
  61. #region Fields
  62. string host;
  63. int port;
  64. int timeout = 100000;
  65. ICredentialsByHost credentials;
  66. string pickupDirectoryLocation;
  67. SmtpDeliveryMethod deliveryMethod;
  68. SmtpDeliveryFormat deliveryFormat;
  69. bool enableSsl;
  70. #if SECURITY_DEP
  71. X509CertificateCollection clientCertificates;
  72. #endif
  73. TcpClient client;
  74. Stream stream;
  75. StreamWriter writer;
  76. StreamReader reader;
  77. int boundaryIndex;
  78. MailAddress defaultFrom;
  79. MailMessage messageInProcess;
  80. BackgroundWorker worker;
  81. object user_async_state;
  82. [Flags]
  83. enum AuthMechs {
  84. None = 0,
  85. Login = 0x01,
  86. Plain = 0x02,
  87. }
  88. class CancellationException : Exception
  89. {
  90. }
  91. AuthMechs authMechs;
  92. Mutex mutex = new Mutex ();
  93. #endregion // Fields
  94. #region Constructors
  95. public SmtpClient ()
  96. : this (null, 0)
  97. {
  98. }
  99. public SmtpClient (string host)
  100. : this (host, 0)
  101. {
  102. }
  103. public SmtpClient (string host, int port) {
  104. #if CONFIGURATION_DEP
  105. SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
  106. if (cfg != null) {
  107. this.host = cfg.Network.Host;
  108. this.port = cfg.Network.Port;
  109. this.enableSsl = cfg.Network.EnableSsl;
  110. TargetName = cfg.Network.TargetName;
  111. if (this.TargetName == null)
  112. TargetName = "SMTPSVC/" + (host != null ? host : "");
  113. if (cfg.Network.UserName != null) {
  114. string password = String.Empty;
  115. if (cfg.Network.Password != null)
  116. password = cfg.Network.Password;
  117. Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
  118. }
  119. if (!String.IsNullOrEmpty (cfg.From))
  120. defaultFrom = new MailAddress (cfg.From);
  121. }
  122. #else
  123. // Just to eliminate the warning, this codepath does not end up in production.
  124. defaultFrom = null;
  125. #endif
  126. if (!String.IsNullOrEmpty (host))
  127. this.host = host;
  128. if (port != 0)
  129. this.port = port;
  130. else if (this.port == 0)
  131. this.port = 25;
  132. }
  133. #endregion // Constructors
  134. #region Properties
  135. #if SECURITY_DEP
  136. [MonoTODO("Client certificates not used")]
  137. public X509CertificateCollection ClientCertificates {
  138. get {
  139. if (clientCertificates == null)
  140. clientCertificates = new X509CertificateCollection ();
  141. return clientCertificates;
  142. }
  143. }
  144. #endif
  145. public
  146. string TargetName { get; set; }
  147. public ICredentialsByHost Credentials {
  148. get { return credentials; }
  149. set {
  150. CheckState ();
  151. credentials = value;
  152. }
  153. }
  154. public SmtpDeliveryMethod DeliveryMethod {
  155. get { return deliveryMethod; }
  156. set {
  157. CheckState ();
  158. deliveryMethod = value;
  159. }
  160. }
  161. public bool EnableSsl {
  162. get { return enableSsl; }
  163. set {
  164. CheckState ();
  165. enableSsl = value;
  166. }
  167. }
  168. public string Host {
  169. get { return host; }
  170. set {
  171. if (value == null)
  172. throw new ArgumentNullException ("value");
  173. if (value.Length == 0)
  174. throw new ArgumentException ("An empty string is not allowed.", "value");
  175. CheckState ();
  176. host = value;
  177. }
  178. }
  179. public string PickupDirectoryLocation {
  180. get { return pickupDirectoryLocation; }
  181. set { pickupDirectoryLocation = value; }
  182. }
  183. public int Port {
  184. get { return port; }
  185. set {
  186. if (value <= 0)
  187. throw new ArgumentOutOfRangeException ("value");
  188. CheckState ();
  189. port = value;
  190. }
  191. }
  192. public SmtpDeliveryFormat DeliveryFormat {
  193. get { return deliveryFormat; }
  194. set {
  195. CheckState ();
  196. deliveryFormat = 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 = MailMessage.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 MailMessage.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 host name (not fully qualified)
  502. string fqdn = Dns.GetHostName ();
  503. try {
  504. // we'll try for the fully qualified name - ref: bug #33551
  505. fqdn = Dns.GetHostEntry (fqdn).HostName;
  506. }
  507. catch (SocketException) {
  508. // we could not resolve our name but will continue with the partial name
  509. // IOW we won't fail to send email because of this - ref: bug #37246
  510. }
  511. status = SendCommand ("EHLO " + fqdn);
  512. if (IsError (status)) {
  513. status = SendCommand ("HELO " + fqdn);
  514. if (IsError (status))
  515. throw new SmtpException (status.StatusCode, status.Description);
  516. } else {
  517. // Parse ESMTP extensions
  518. string extens = status.Description;
  519. if (extens != null)
  520. ParseExtensions (extens);
  521. }
  522. if (enableSsl) {
  523. InitiateSecureConnection ();
  524. ResetExtensions();
  525. writer = new StreamWriter (stream);
  526. reader = new StreamReader (stream);
  527. status = SendCommand ("EHLO " + fqdn);
  528. if (IsError (status)) {
  529. status = SendCommand ("HELO " + fqdn);
  530. if (IsError (status))
  531. throw new SmtpException (status.StatusCode, status.Description);
  532. } else {
  533. // Parse ESMTP extensions
  534. string extens = status.Description;
  535. if (extens != null)
  536. ParseExtensions (extens);
  537. }
  538. }
  539. if (authMechs != AuthMechs.None)
  540. Authenticate ();
  541. // The envelope sender: use 'Sender:' in preference of 'From:'
  542. MailAddress sender = message.Sender;
  543. if (sender == null)
  544. sender = message.From;
  545. if (sender == null)
  546. sender = defaultFrom;
  547. // MAIL FROM:
  548. status = SendCommand ("MAIL FROM:<" + sender.Address + '>');
  549. if (IsError (status)) {
  550. throw new SmtpException (status.StatusCode, status.Description);
  551. }
  552. // Send RCPT TO: for all recipients
  553. List<SmtpFailedRecipientException> sfre = new List<SmtpFailedRecipientException> ();
  554. for (int i = 0; i < message.To.Count; i ++) {
  555. status = SendCommand ("RCPT TO:<" + message.To [i].Address + '>');
  556. if (IsError (status))
  557. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.To [i].Address));
  558. }
  559. for (int i = 0; i < message.CC.Count; i ++) {
  560. status = SendCommand ("RCPT TO:<" + message.CC [i].Address + '>');
  561. if (IsError (status))
  562. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.CC [i].Address));
  563. }
  564. for (int i = 0; i < message.Bcc.Count; i ++) {
  565. status = SendCommand ("RCPT TO:<" + message.Bcc [i].Address + '>');
  566. if (IsError (status))
  567. sfre.Add (new SmtpFailedRecipientException (status.StatusCode, message.Bcc [i].Address));
  568. }
  569. if (sfre.Count >0)
  570. throw new SmtpFailedRecipientsException ("failed recipients", sfre.ToArray ());
  571. // DATA
  572. status = SendCommand ("DATA");
  573. if (IsError (status))
  574. throw new SmtpException (status.StatusCode, status.Description);
  575. // Send message headers
  576. string dt = DateTime.Now.ToString ("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
  577. // remove ':' from time zone offset (e.g. from "+01:00")
  578. dt = dt.Remove (dt.Length - 3, 1);
  579. SendHeader (HeaderName.Date, dt);
  580. MailAddress from = message.From;
  581. if (from == null)
  582. from = defaultFrom;
  583. SendHeader (HeaderName.From, EncodeAddress (from));
  584. SendHeader (HeaderName.To, EncodeAddresses (message.To));
  585. if (message.CC.Count > 0)
  586. SendHeader (HeaderName.Cc, EncodeAddresses (message.CC));
  587. SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
  588. string v = "normal";
  589. switch (message.Priority){
  590. case MailPriority.Normal:
  591. v = "normal";
  592. break;
  593. case MailPriority.Low:
  594. v = "non-urgent";
  595. break;
  596. case MailPriority.High:
  597. v = "urgent";
  598. break;
  599. }
  600. SendHeader ("Priority", v);
  601. if (message.Sender != null)
  602. SendHeader ("Sender", EncodeAddress (message.Sender));
  603. if (message.ReplyToList.Count > 0)
  604. SendHeader ("Reply-To", EncodeAddresses (message.ReplyToList));
  605. foreach (string s in message.Headers.AllKeys)
  606. SendHeader (s, MailMessage.EncodeSubjectRFC2047 (message.Headers [s], message.HeadersEncoding));
  607. AddPriorityHeader (message);
  608. boundaryIndex = 0;
  609. if (message.Attachments.Count > 0)
  610. SendWithAttachments (message);
  611. else
  612. SendWithoutAttachments (message, null, false);
  613. SendDot ();
  614. status = Read ();
  615. if (IsError (status))
  616. throw new SmtpException (status.StatusCode, status.Description);
  617. try {
  618. status = SendCommand ("QUIT");
  619. } catch (System.IO.IOException) {
  620. // We excuse server for the rude connection closing as a response to QUIT
  621. }
  622. }
  623. public void Send (string from, string to, string subject, string body)
  624. {
  625. Send (new MailMessage (from, to, subject, body));
  626. }
  627. public Task SendMailAsync (MailMessage message)
  628. {
  629. var tcs = new TaskCompletionSource<object> ();
  630. SendCompletedEventHandler handler = null;
  631. handler = (s, e) => SendMailAsyncCompletedHandler (tcs, e, handler, this);
  632. SendCompleted += handler;
  633. SendAsync (message, tcs);
  634. return tcs.Task;
  635. }
  636. public Task SendMailAsync (string from, string recipients, string subject, string body)
  637. {
  638. return SendMailAsync (new MailMessage (from, recipients, subject, body));
  639. }
  640. static void SendMailAsyncCompletedHandler (TaskCompletionSource<object> source, AsyncCompletedEventArgs e, SendCompletedEventHandler handler, SmtpClient client)
  641. {
  642. if (source != e.UserState)
  643. return;
  644. client.SendCompleted -= handler;
  645. if (e.Error != null) {
  646. source.SetException (e.Error);
  647. return;
  648. }
  649. if (e.Cancelled) {
  650. source.SetCanceled ();
  651. return;
  652. }
  653. source.SetResult (null);
  654. }
  655. private void SendDot()
  656. {
  657. writer.Write(".\r\n");
  658. writer.Flush();
  659. }
  660. private void SendData (string data)
  661. {
  662. if (String.IsNullOrEmpty (data)) {
  663. writer.Write("\r\n");
  664. writer.Flush();
  665. return;
  666. }
  667. StringReader sr = new StringReader (data);
  668. string line;
  669. bool escapeDots = deliveryMethod == SmtpDeliveryMethod.Network;
  670. while ((line = sr.ReadLine ()) != null) {
  671. CheckCancellation ();
  672. if (escapeDots) {
  673. if (line.Length > 0 && line[0] == '.') {
  674. line = "." + line;
  675. }
  676. }
  677. writer.Write (line);
  678. writer.Write ("\r\n");
  679. }
  680. writer.Flush ();
  681. }
  682. public void SendAsync (MailMessage message, object userToken)
  683. {
  684. if (worker != null)
  685. throw new InvalidOperationException ("Another SendAsync operation is in progress");
  686. worker = new BackgroundWorker ();
  687. worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
  688. try {
  689. user_async_state = ea.Argument;
  690. Send (message);
  691. } catch (Exception ex) {
  692. ea.Result = ex;
  693. throw ex;
  694. }
  695. };
  696. worker.WorkerSupportsCancellation = true;
  697. worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
  698. // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
  699. OnSendCompleted (new AsyncCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state));
  700. };
  701. worker.RunWorkerAsync (userToken);
  702. }
  703. public void SendAsync (string from, string to, string subject, string body, object userToken)
  704. {
  705. SendAsync (new MailMessage (from, to, subject, body), userToken);
  706. }
  707. public void SendAsyncCancel ()
  708. {
  709. if (worker == null)
  710. throw new InvalidOperationException ("SendAsync operation is not in progress");
  711. worker.CancelAsync ();
  712. }
  713. private void AddPriorityHeader (MailMessage message) {
  714. switch (message.Priority) {
  715. case MailPriority.High:
  716. SendHeader (HeaderName.Priority, "Urgent");
  717. SendHeader (HeaderName.Importance, "high");
  718. SendHeader (HeaderName.XPriority, "1");
  719. break;
  720. case MailPriority.Low:
  721. SendHeader (HeaderName.Priority, "Non-Urgent");
  722. SendHeader (HeaderName.Importance, "low");
  723. SendHeader (HeaderName.XPriority, "5");
  724. break;
  725. }
  726. }
  727. private void SendSimpleBody (MailMessage message) {
  728. SendHeader (HeaderName.ContentType, message.BodyContentType.ToString ());
  729. if (message.ContentTransferEncoding != TransferEncoding.SevenBit)
  730. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (message.ContentTransferEncoding));
  731. SendData (string.Empty);
  732. SendData (EncodeBody (message));
  733. }
  734. private void SendBodylessSingleAlternate (AlternateView av) {
  735. SendHeader (HeaderName.ContentType, av.ContentType.ToString ());
  736. if (av.TransferEncoding != TransferEncoding.SevenBit)
  737. SendHeader (HeaderName.ContentTransferEncoding, GetTransferEncodingName (av.TransferEncoding));
  738. SendData (string.Empty);
  739. SendData (EncodeBody (av));
  740. }
  741. private void SendWithoutAttachments (MailMessage message, string boundary, bool attachmentExists)
  742. {
  743. if (message.Body == null && message.AlternateViews.Count == 1)
  744. SendBodylessSingleAlternate (message.AlternateViews [0]);
  745. else if (message.AlternateViews.Count > 0)
  746. SendBodyWithAlternateViews (message, boundary, attachmentExists);
  747. else
  748. SendSimpleBody (message);
  749. }
  750. private void SendWithAttachments (MailMessage message) {
  751. string boundary = GenerateBoundary ();
  752. // first "multipart/mixed"
  753. ContentType messageContentType = new ContentType ();
  754. messageContentType.Boundary = boundary;
  755. messageContentType.MediaType = "multipart/mixed";
  756. messageContentType.CharSet = null;
  757. SendHeader (HeaderName.ContentType, messageContentType.ToString ());
  758. SendData (String.Empty);
  759. // body section
  760. Attachment body = null;
  761. if (message.AlternateViews.Count > 0)
  762. SendWithoutAttachments (message, boundary, true);
  763. else {
  764. body = Attachment.CreateAttachmentFromString (message.Body, null, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
  765. message.Attachments.Insert (0, body);
  766. }
  767. try {
  768. SendAttachments (message, body, boundary);
  769. } finally {
  770. if (body != null)
  771. message.Attachments.Remove (body);
  772. }
  773. EndSection (boundary);
  774. }
  775. private void SendBodyWithAlternateViews (MailMessage message, string boundary, bool attachmentExists)
  776. {
  777. AlternateViewCollection alternateViews = message.AlternateViews;
  778. string inner_boundary = GenerateBoundary ();
  779. ContentType messageContentType = new ContentType ();
  780. messageContentType.Boundary = inner_boundary;
  781. messageContentType.MediaType = "multipart/alternative";
  782. if (!attachmentExists) {
  783. SendHeader (HeaderName.ContentType, messageContentType.ToString ());
  784. SendData (String.Empty);
  785. }
  786. // body section
  787. AlternateView body = null;
  788. if (message.Body != null) {
  789. body = AlternateView.CreateAlternateViewFromString (message.Body, message.BodyEncoding, message.IsBodyHtml ? "text/html" : "text/plain");
  790. alternateViews.Insert (0, body);
  791. StartSection (boundary, messageContentType);
  792. }
  793. try {
  794. // alternate view sections
  795. foreach (AlternateView av in alternateViews) {
  796. string alt_boundary = null;
  797. ContentType contentType;
  798. if (av.LinkedResources.Count > 0) {
  799. alt_boundary = GenerateBoundary ();
  800. contentType = new ContentType ("multipart/related");
  801. contentType.Boundary = alt_boundary;
  802. contentType.Parameters ["type"] = av.ContentType.ToString ();
  803. StartSection (inner_boundary, contentType);
  804. StartSection (alt_boundary, av.ContentType, av);
  805. } else {
  806. contentType = new ContentType (av.ContentType.ToString ());
  807. StartSection (inner_boundary, contentType, av);
  808. }
  809. switch (av.TransferEncoding) {
  810. case TransferEncoding.Base64:
  811. byte [] content = new byte [av.ContentStream.Length];
  812. av.ContentStream.Read (content, 0, content.Length);
  813. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  814. break;
  815. case TransferEncoding.QuotedPrintable:
  816. byte [] bytes = new byte [av.ContentStream.Length];
  817. av.ContentStream.Read (bytes, 0, bytes.Length);
  818. SendData (ToQuotedPrintable (bytes));
  819. break;
  820. case TransferEncoding.SevenBit:
  821. case TransferEncoding.Unknown:
  822. content = new byte [av.ContentStream.Length];
  823. av.ContentStream.Read (content, 0, content.Length);
  824. SendData (Encoding.ASCII.GetString (content));
  825. break;
  826. }
  827. if (av.LinkedResources.Count > 0) {
  828. SendLinkedResources (message, av.LinkedResources, alt_boundary);
  829. EndSection (alt_boundary);
  830. }
  831. if (!attachmentExists)
  832. SendData (string.Empty);
  833. }
  834. } finally {
  835. if (body != null)
  836. alternateViews.Remove (body);
  837. }
  838. EndSection (inner_boundary);
  839. }
  840. private void SendLinkedResources (MailMessage message, LinkedResourceCollection resources, string boundary)
  841. {
  842. foreach (LinkedResource lr in resources) {
  843. StartSection (boundary, lr.ContentType, lr);
  844. switch (lr.TransferEncoding) {
  845. case TransferEncoding.Base64:
  846. byte [] content = new byte [lr.ContentStream.Length];
  847. lr.ContentStream.Read (content, 0, content.Length);
  848. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  849. break;
  850. case TransferEncoding.QuotedPrintable:
  851. byte [] bytes = new byte [lr.ContentStream.Length];
  852. lr.ContentStream.Read (bytes, 0, bytes.Length);
  853. SendData (ToQuotedPrintable (bytes));
  854. break;
  855. case TransferEncoding.SevenBit:
  856. case TransferEncoding.Unknown:
  857. content = new byte [lr.ContentStream.Length];
  858. lr.ContentStream.Read (content, 0, content.Length);
  859. SendData (Encoding.ASCII.GetString (content));
  860. break;
  861. }
  862. }
  863. }
  864. private void SendAttachments (MailMessage message, Attachment body, string boundary) {
  865. foreach (Attachment att in message.Attachments) {
  866. ContentType contentType = new ContentType (att.ContentType.ToString ());
  867. if (att.Name != null) {
  868. contentType.Name = att.Name;
  869. if (att.NameEncoding != null)
  870. contentType.CharSet = att.NameEncoding.HeaderName;
  871. att.ContentDisposition.FileName = att.Name;
  872. }
  873. StartSection (boundary, contentType, att, att != body);
  874. byte [] content = new byte [att.ContentStream.Length];
  875. att.ContentStream.Read (content, 0, content.Length);
  876. switch (att.TransferEncoding) {
  877. case TransferEncoding.Base64:
  878. SendData (Convert.ToBase64String (content, Base64FormattingOptions.InsertLineBreaks));
  879. break;
  880. case TransferEncoding.QuotedPrintable:
  881. SendData (ToQuotedPrintable (content));
  882. break;
  883. case TransferEncoding.SevenBit:
  884. case TransferEncoding.Unknown:
  885. SendData (Encoding.ASCII.GetString (content));
  886. break;
  887. }
  888. SendData (string.Empty);
  889. }
  890. }
  891. private SmtpResponse SendCommand (string command)
  892. {
  893. writer.Write (command);
  894. // Certain SMTP servers will reject mail sent with unix line-endings; see http://cr.yp.to/docs/smtplf.html
  895. writer.Write ("\r\n");
  896. writer.Flush ();
  897. return Read ();
  898. }
  899. private void SendHeader (string name, string value)
  900. {
  901. SendData (String.Format ("{0}: {1}", name, value));
  902. }
  903. private void StartSection (string section, ContentType sectionContentType)
  904. {
  905. SendData (String.Format ("--{0}", section));
  906. SendHeader ("content-type", sectionContentType.ToString ());
  907. SendData (string.Empty);
  908. }
  909. private void StartSection (string section, ContentType sectionContentType, AttachmentBase att)
  910. {
  911. SendData (String.Format ("--{0}", section));
  912. SendHeader ("content-type", sectionContentType.ToString ());
  913. SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
  914. if (!string.IsNullOrEmpty (att.ContentId))
  915. SendHeader("content-ID", "<" + att.ContentId + ">");
  916. SendData (string.Empty);
  917. }
  918. private void StartSection (string section, ContentType sectionContentType, Attachment att, bool sendDisposition) {
  919. SendData (String.Format ("--{0}", section));
  920. if (!string.IsNullOrEmpty (att.ContentId))
  921. SendHeader("content-ID", "<" + att.ContentId + ">");
  922. SendHeader ("content-type", sectionContentType.ToString ());
  923. SendHeader ("content-transfer-encoding", GetTransferEncodingName (att.TransferEncoding));
  924. if (sendDisposition)
  925. SendHeader ("content-disposition", att.ContentDisposition.ToString ());
  926. SendData (string.Empty);
  927. }
  928. // use proper encoding to escape input
  929. private string ToQuotedPrintable (string input, Encoding enc)
  930. {
  931. byte [] bytes = enc.GetBytes (input);
  932. return ToQuotedPrintable (bytes);
  933. }
  934. private string ToQuotedPrintable (byte [] bytes)
  935. {
  936. StringWriter writer = new StringWriter ();
  937. int charsInLine = 0;
  938. int curLen;
  939. StringBuilder sb = new StringBuilder("=", 3);
  940. byte equalSign = (byte)'=';
  941. char c = (char)0;
  942. foreach (byte i in bytes) {
  943. if (i > 127 || i == equalSign) {
  944. sb.Length = 1;
  945. sb.Append(Convert.ToString (i, 16).ToUpperInvariant ());
  946. curLen = 3;
  947. } else {
  948. c = Convert.ToChar (i);
  949. if (c == '\r' || c == '\n') {
  950. writer.Write (c);
  951. charsInLine = 0;
  952. continue;
  953. }
  954. curLen = 1;
  955. }
  956. charsInLine += curLen;
  957. if (charsInLine > 75) {
  958. writer.Write ("=\r\n");
  959. charsInLine = curLen;
  960. }
  961. if (curLen == 1)
  962. writer.Write (c);
  963. else
  964. writer.Write (sb.ToString ());
  965. }
  966. return writer.ToString ();
  967. }
  968. private static string GetTransferEncodingName (TransferEncoding encoding)
  969. {
  970. switch (encoding) {
  971. case TransferEncoding.QuotedPrintable:
  972. return "quoted-printable";
  973. case TransferEncoding.SevenBit:
  974. return "7bit";
  975. case TransferEncoding.Base64:
  976. return "base64";
  977. }
  978. return "unknown";
  979. }
  980. private void InitiateSecureConnection () {
  981. SmtpResponse response = SendCommand ("STARTTLS");
  982. if (IsError (response)) {
  983. throw new SmtpException (SmtpStatusCode.GeneralFailure, "Server does not support secure connections.");
  984. }
  985. #if SECURITY_DEP
  986. var tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
  987. var settings = MSI.MonoTlsSettings.CopyDefaultSettings ();
  988. settings.UseServicePointManagerCallback = true;
  989. var sslStream = tlsProvider.CreateSslStream (stream, false, settings);
  990. CheckCancellation ();
  991. sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
  992. stream = sslStream.AuthenticatedStream;
  993. #else
  994. throw new SystemException ("You are using an incomplete System.dll build");
  995. #endif
  996. }
  997. void Authenticate ()
  998. {
  999. string user = null, pass = null;
  1000. if (UseDefaultCredentials) {
  1001. user = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").UserName;
  1002. pass = CredentialCache.DefaultCredentials.GetCredential (new System.Uri ("smtp://" + host), "basic").Password;
  1003. } else if (Credentials != null) {
  1004. user = Credentials.GetCredential (host, port, "smtp").UserName;
  1005. pass = Credentials.GetCredential (host, port, "smtp").Password;
  1006. } else {
  1007. return;
  1008. }
  1009. Authenticate (user, pass);
  1010. }
  1011. void CheckStatus (SmtpResponse status, int i)
  1012. {
  1013. if (((int) status.StatusCode) != i)
  1014. throw new SmtpException (status.StatusCode, status.Description);
  1015. }
  1016. void ThrowIfError (SmtpResponse status)
  1017. {
  1018. if (IsError (status))
  1019. throw new SmtpException (status.StatusCode, status.Description);
  1020. }
  1021. void Authenticate (string user, string password)
  1022. {
  1023. if (authMechs == AuthMechs.None)
  1024. return;
  1025. SmtpResponse status;
  1026. /*
  1027. if ((authMechs & AuthMechs.DigestMD5) != 0) {
  1028. status = SendCommand ("AUTH DIGEST-MD5");
  1029. CheckStatus (status, 334);
  1030. string challenge = Encoding.ASCII.GetString (Convert.FromBase64String (status.Description.Substring (4)));
  1031. Console.WriteLine ("CHALLENGE: {0}", challenge);
  1032. DigestSession session = new DigestSession ();
  1033. session.Parse (false, challenge);
  1034. string response = session.Authenticate (this, user, password);
  1035. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (response)));
  1036. CheckStatus (status, 235);
  1037. } else */
  1038. if ((authMechs & AuthMechs.Login) != 0) {
  1039. status = SendCommand ("AUTH LOGIN");
  1040. CheckStatus (status, 334);
  1041. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (user)));
  1042. CheckStatus (status, 334);
  1043. status = SendCommand (Convert.ToBase64String (Encoding.UTF8.GetBytes (password)));
  1044. CheckStatus (status, 235);
  1045. } else if ((authMechs & AuthMechs.Plain) != 0) {
  1046. string s = String.Format ("\0{0}\0{1}", user, password);
  1047. s = Convert.ToBase64String (Encoding.UTF8.GetBytes (s));
  1048. status = SendCommand ("AUTH PLAIN " + s);
  1049. CheckStatus (status, 235);
  1050. } else {
  1051. throw new SmtpException ("AUTH types PLAIN, LOGIN not supported by the server");
  1052. }
  1053. }
  1054. #endregion // Methods
  1055. // The HeaderName struct is used to store constant string values representing mail headers.
  1056. private struct HeaderName {
  1057. public const string ContentTransferEncoding = "Content-Transfer-Encoding";
  1058. public const string ContentType = "Content-Type";
  1059. public const string Bcc = "Bcc";
  1060. public const string Cc = "Cc";
  1061. public const string From = "From";
  1062. public const string Subject = "Subject";
  1063. public const string To = "To";
  1064. public const string MimeVersion = "MIME-Version";
  1065. public const string MessageId = "Message-ID";
  1066. public const string Priority = "Priority";
  1067. public const string Importance = "Importance";
  1068. public const string XPriority = "X-Priority";
  1069. public const string Date = "Date";
  1070. }
  1071. // This object encapsulates the status code and description of an SMTP response.
  1072. private struct SmtpResponse {
  1073. public SmtpStatusCode StatusCode;
  1074. public string Description;
  1075. public static SmtpResponse Parse (string line) {
  1076. SmtpResponse response = new SmtpResponse ();
  1077. if (line.Length < 4)
  1078. throw new SmtpException ("Response is to short " +
  1079. line.Length + ".");
  1080. if ((line [3] != ' ') && (line [3] != '-'))
  1081. throw new SmtpException ("Response format is wrong.(" +
  1082. line + ")");
  1083. // parse the response code
  1084. response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));
  1085. // set the raw response
  1086. response.Description = line;
  1087. return response;
  1088. }
  1089. }
  1090. }
  1091. class CCredentialsByHost : ICredentialsByHost
  1092. {
  1093. public CCredentialsByHost (string userName, string password) {
  1094. this.userName = userName;
  1095. this.password = password;
  1096. }
  1097. public NetworkCredential GetCredential (string host, int port, string authenticationType) {
  1098. return new NetworkCredential (userName, password);
  1099. }
  1100. private string userName;
  1101. private string password;
  1102. }
  1103. }