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_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. bool enableSsl;
  69. #if SECURITY_DEP
  70. X509CertificateCollection clientCertificates;
  71. #endif
  72. TcpClient client;
  73. Stream stream;
  74. StreamWriter writer;
  75. StreamReader reader;
  76. int boundaryIndex;
  77. MailAddress defaultFrom;
  78. MailMessage messageInProcess;
  79. BackgroundWorker worker;
  80. object user_async_state;
  81. [Flags]
  82. enum AuthMechs {
  83. None = 0,
  84. Login = 0x01,
  85. Plain = 0x02,
  86. }
  87. class CancellationException : Exception
  88. {
  89. }
  90. AuthMechs authMechs;
  91. Mutex mutex = new Mutex ();
  92. #endregion // Fields
  93. #region Constructors
  94. public SmtpClient ()
  95. : this (null, 0)
  96. {
  97. }
  98. public SmtpClient (string host)
  99. : this (host, 0)
  100. {
  101. }
  102. public SmtpClient (string host, int port) {
  103. #if CONFIGURATION_DEP
  104. SmtpSection cfg = (SmtpSection) ConfigurationManager.GetSection ("system.net/mailSettings/smtp");
  105. if (cfg != null) {
  106. this.host = cfg.Network.Host;
  107. this.port = cfg.Network.Port;
  108. this.enableSsl = cfg.Network.EnableSsl;
  109. TargetName = cfg.Network.TargetName;
  110. if (this.TargetName == null)
  111. TargetName = "SMTPSVC/" + (host != null ? host : "");
  112. if (cfg.Network.UserName != null) {
  113. string password = String.Empty;
  114. if (cfg.Network.Password != null)
  115. password = cfg.Network.Password;
  116. Credentials = new CCredentialsByHost (cfg.Network.UserName, password);
  117. }
  118. if (!String.IsNullOrEmpty (cfg.From))
  119. defaultFrom = new MailAddress (cfg.From);
  120. }
  121. #else
  122. // Just to eliminate the warning, this codepath does not end up in production.
  123. defaultFrom = null;
  124. #endif
  125. if (!String.IsNullOrEmpty (host))
  126. this.host = host;
  127. if (port != 0)
  128. this.port = port;
  129. else if (this.port == 0)
  130. this.port = 25;
  131. }
  132. #endregion // Constructors
  133. #region Properties
  134. #if SECURITY_DEP
  135. [MonoTODO("Client certificates not used")]
  136. public X509CertificateCollection ClientCertificates {
  137. get {
  138. if (clientCertificates == null)
  139. clientCertificates = new X509CertificateCollection ();
  140. return clientCertificates;
  141. }
  142. }
  143. #endif
  144. public
  145. string TargetName { get; set; }
  146. public ICredentialsByHost Credentials {
  147. get { return credentials; }
  148. set {
  149. CheckState ();
  150. credentials = value;
  151. }
  152. }
  153. public SmtpDeliveryMethod DeliveryMethod {
  154. get { return deliveryMethod; }
  155. set {
  156. CheckState ();
  157. deliveryMethod = value;
  158. }
  159. }
  160. public bool EnableSsl {
  161. get { return enableSsl; }
  162. set {
  163. CheckState ();
  164. enableSsl = value;
  165. }
  166. }
  167. public string Host {
  168. get { return host; }
  169. set {
  170. if (value == null)
  171. throw new ArgumentNullException ("value");
  172. if (value.Length == 0)
  173. throw new ArgumentException ("An empty string is not allowed.", "value");
  174. CheckState ();
  175. host = value;
  176. }
  177. }
  178. public string PickupDirectoryLocation {
  179. get { return pickupDirectoryLocation; }
  180. set { pickupDirectoryLocation = value; }
  181. }
  182. public int Port {
  183. get { return port; }
  184. set {
  185. if (value <= 0)
  186. throw new ArgumentOutOfRangeException ("value");
  187. CheckState ();
  188. port = value;
  189. }
  190. }
  191. [MonoTODO]
  192. public ServicePoint ServicePoint {
  193. get { throw new NotImplementedException (); }
  194. }
  195. public int Timeout {
  196. get { return timeout; }
  197. set {
  198. if (value < 0)
  199. throw new ArgumentOutOfRangeException ("value");
  200. CheckState ();
  201. timeout = value;
  202. }
  203. }
  204. public bool UseDefaultCredentials {
  205. get { return false; }
  206. [MonoNotSupported ("no DefaultCredential support in Mono")]
  207. set {
  208. if (value)
  209. throw new NotImplementedException ("Default credentials are not supported");
  210. CheckState ();
  211. }
  212. }
  213. #endregion // Properties
  214. #region Events
  215. public event SendCompletedEventHandler SendCompleted;
  216. #endregion // Events
  217. #region Methods
  218. public void Dispose ()
  219. {
  220. Dispose (true);
  221. }
  222. [MonoTODO ("Does nothing at the moment.")]
  223. protected virtual void Dispose (bool disposing)
  224. {
  225. // TODO: We should close all the connections and abort any async operations here
  226. }
  227. private void CheckState ()
  228. {
  229. if (messageInProcess != null)
  230. throw new InvalidOperationException ("Cannot set Timeout while Sending a message");
  231. }
  232. private static string EncodeAddress(MailAddress address)
  233. {
  234. if (!String.IsNullOrEmpty (address.DisplayName)) {
  235. string encodedDisplayName = MailMessage.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
  236. return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
  237. }
  238. return address.ToString ();
  239. }
  240. private static string EncodeAddresses(MailAddressCollection addresses)
  241. {
  242. StringBuilder sb = new StringBuilder();
  243. bool first = true;
  244. foreach (MailAddress address in addresses) {
  245. if (!first) {
  246. sb.Append(", ");
  247. }
  248. sb.Append(EncodeAddress(address));
  249. first = false;
  250. }
  251. return sb.ToString();
  252. }
  253. private string EncodeSubjectRFC2047 (MailMessage message)
  254. {
  255. return MailMessage.EncodeSubjectRFC2047 (message.Subject, message.SubjectEncoding);
  256. }
  257. private string EncodeBody (MailMessage message)
  258. {
  259. string body = message.Body;
  260. Encoding encoding = message.BodyEncoding;
  261. // RFC 2045 encoding
  262. switch (message.ContentTransferEncoding) {
  263. case TransferEncoding.SevenBit:
  264. return body;
  265. case TransferEncoding.Base64:
  266. return Convert.ToBase64String (encoding.GetBytes (body), Base64FormattingOptions.InsertLineBreaks);
  267. default:
  268. return ToQuotedPrintable (body, encoding);
  269. }
  270. }
  271. private string EncodeBody (AlternateView av)
  272. {
  273. //Encoding encoding = av.ContentType.CharSet != null ? Encoding.GetEncoding (av.ContentType.CharSet) : Encoding.UTF8;
  274. byte [] bytes = new byte [av.ContentStream.Length];
  275. av.ContentStream.Read (bytes, 0, bytes.Length);
  276. // RFC 2045 encoding
  277. switch (av.TransferEncoding) {
  278. case TransferEncoding.SevenBit:
  279. return Encoding.ASCII.GetString (bytes);
  280. case TransferEncoding.Base64:
  281. return Convert.ToBase64String (bytes, Base64FormattingOptions.InsertLineBreaks);
  282. default:
  283. return ToQuotedPrintable (bytes);
  284. }
  285. }
  286. private void EndSection (string section)
  287. {
  288. SendData (String.Format ("--{0}--", section));
  289. SendData (string.Empty);
  290. }
  291. private string GenerateBoundary ()
  292. {
  293. string output = GenerateBoundary (boundaryIndex);
  294. boundaryIndex += 1;
  295. return output;
  296. }
  297. private static string GenerateBoundary (int index)
  298. {
  299. return String.Format ("--boundary_{0}_{1}", index, Guid.NewGuid ().ToString ("D"));
  300. }
  301. private bool IsError (SmtpResponse status)
  302. {
  303. return ((int) status.StatusCode) >= 400;
  304. }
  305. protected void OnSendCompleted (AsyncCompletedEventArgs e)
  306. {
  307. try {
  308. if (SendCompleted != null)
  309. SendCompleted (this, e);
  310. } finally {
  311. worker = null;
  312. user_async_state = null;
  313. }
  314. }
  315. private void CheckCancellation ()
  316. {
  317. if (worker != null && worker.CancellationPending)
  318. throw new CancellationException ();
  319. }
  320. private SmtpResponse Read () {
  321. byte [] buffer = new byte [512];
  322. int position = 0;
  323. bool lastLine = false;
  324. do {
  325. CheckCancellation ();
  326. int readLength = stream.Read (buffer, position, buffer.Length - position);
  327. if (readLength > 0) {
  328. int available = position + readLength - 1;
  329. if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
  330. for (int index = available - 3; ; index--) {
  331. if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r') {
  332. lastLine = buffer [index + 4] == ' ';
  333. break;
  334. }
  335. }
  336. // move position
  337. position += readLength;
  338. // check if buffer is full
  339. if (position == buffer.Length) {
  340. byte [] newBuffer = new byte [buffer.Length * 2];
  341. Array.Copy (buffer, 0, newBuffer, 0, buffer.Length);
  342. buffer = newBuffer;
  343. }
  344. }
  345. else {
  346. break;
  347. }
  348. } while (!lastLine);
  349. if (position > 0) {
  350. Encoding encoding = new ASCIIEncoding ();
  351. string line = encoding.GetString (buffer, 0, position - 1);
  352. // parse the line to the lastResponse object
  353. SmtpResponse response = SmtpResponse.Parse (line);
  354. return response;
  355. } else {
  356. throw new System.IO.IOException ("Connection closed");
  357. }
  358. }
  359. void ResetExtensions()
  360. {
  361. authMechs = AuthMechs.None;
  362. }
  363. void ParseExtensions (string extens)
  364. {
  365. string[] parts = extens.Split ('\n');
  366. foreach (string part in parts) {
  367. if (part.Length < 4)
  368. continue;
  369. string start = part.Substring (4);
  370. if (start.StartsWith ("AUTH ", StringComparison.Ordinal)) {
  371. string[] options = start.Split (' ');
  372. for (int k = 1; k < options.Length; k++) {
  373. string option = options[k].Trim();
  374. // GSSAPI, KERBEROS_V4, NTLM not supported
  375. switch (option) {
  376. /*
  377. case "CRAM-MD5":
  378. authMechs |= AuthMechs.CramMD5;
  379. break;
  380. case "DIGEST-MD5":
  381. authMechs |= AuthMechs.DigestMD5;
  382. break;
  383. */
  384. case "LOGIN":
  385. authMechs |= AuthMechs.Login;
  386. break;
  387. case "PLAIN":
  388. authMechs |= AuthMechs.Plain;
  389. break;
  390. }
  391. }
  392. }
  393. }
  394. }
  395. public void Send (MailMessage message)
  396. {
  397. if (message == null)
  398. throw new ArgumentNullException ("message");
  399. if (deliveryMethod == SmtpDeliveryMethod.Network && (Host == null || Host.Trim ().Length == 0))
  400. throw new InvalidOperationException ("The SMTP host was not specified");
  401. else if (deliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
  402. throw new NotSupportedException("IIS delivery is not supported");
  403. if (port == 0)
  404. port = 25;
  405. // Block while sending
  406. mutex.WaitOne ();
  407. try {
  408. messageInProcess = message;
  409. if (deliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
  410. SendToFile (message);
  411. else
  412. SendInternal (message);
  413. } catch (CancellationException) {
  414. // This exception is introduced for convenient cancellation process.
  415. } catch (SmtpException) {
  416. throw;
  417. } catch (Exception ex) {
  418. throw new SmtpException ("Message could not be sent.", ex);
  419. } finally {
  420. // Release the mutex to allow other threads access
  421. mutex.ReleaseMutex ();
  422. messageInProcess = null;
  423. }
  424. }
  425. private void SendInternal (MailMessage message)
  426. {
  427. CheckCancellation ();
  428. try {
  429. client = new TcpClient (host, port);
  430. stream = client.GetStream ();
  431. // FIXME: this StreamWriter creation is bogus.
  432. // It expects as if a Stream were able to switch to SSL
  433. // mode (such behavior is only in Mainsoft Socket API).
  434. writer = new StreamWriter (stream);
  435. reader = new StreamReader (stream);
  436. SendCore (message);
  437. } finally {
  438. if (writer != null)
  439. writer.Close ();
  440. if (reader != null)
  441. reader.Close ();
  442. if (stream != null)
  443. stream.Close ();
  444. if (client != null)
  445. client.Close ();
  446. }
  447. }
  448. // FIXME: simple implementation, could be brushed up.
  449. private void SendToFile (MailMessage message)
  450. {
  451. if (!Path.IsPathRooted (pickupDirectoryLocation))
  452. throw new SmtpException("Only absolute directories are allowed for pickup directory.");
  453. string filename = Path.Combine (pickupDirectoryLocation,
  454. Guid.NewGuid() + ".eml");
  455. try {
  456. writer = new StreamWriter(filename);
  457. // FIXME: See how Microsoft fixed the bug about envelope senders, and how it actually represents the info in .eml file headers
  458. // For all we know, defaultFrom may be the envelope sender
  459. // For now, we are no worse than some versions of .NET
  460. MailAddress from = message.From;
  461. if (from == null)
  462. from = defaultFrom;
  463. string dt = DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo);
  464. // remove ':' from time zone offset (e.g. from "+01:00")
  465. dt = dt.Remove(dt.Length - 3, 1);
  466. SendHeader(HeaderName.Date, dt);
  467. SendHeader (HeaderName.From, EncodeAddress(from));
  468. SendHeader (HeaderName.To, EncodeAddresses(message.To));
  469. if (message.CC.Count > 0)
  470. SendHeader (HeaderName.Cc, EncodeAddresses(message.CC));
  471. SendHeader (HeaderName.Subject, EncodeSubjectRFC2047 (message));
  472. foreach (string s in message.Headers.AllKeys)
  473. SendHeader (s, message.Headers [s]);
  474. AddPriorityHeader (message);
  475. boundaryIndex = 0;
  476. if (message.Attachments.Count > 0)
  477. SendWithAttachments (message);
  478. else
  479. SendWithoutAttachments (message, null, false);
  480. } finally {
  481. if (writer != null) writer.Close(); writer = null;
  482. }
  483. }
  484. private void SendCore (MailMessage message)
  485. {
  486. SmtpResponse status;
  487. status = Read ();
  488. if (IsError (status))
  489. throw new SmtpException (status.StatusCode, status.Description);
  490. // EHLO
  491. // FIXME: parse the list of extensions so we don't bother wasting
  492. // our time trying commands if they aren't supported.
  493. // get the host name (not fully qualified)
  494. string fqdn = Dns.GetHostName ();
  495. try {
  496. // we'll try for the fully qualified name - ref: bug #33551
  497. fqdn = Dns.GetHostEntry (fqdn).HostName;
  498. }
  499. catch (SocketException) {
  500. // we could not resolve our name but will continue with the partial name
  501. // IOW we won't fail to send email because of this - ref: bug #37246
  502. }
  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, MailMessage.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. }