SmtpClient.cs 37 KB

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