SmtpClient.cs 36 KB

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